NodeCanvas Forums › General Discussion › Dialogue Trees Component for UI Toolkit
Tagged: UI Toolkit
Hello, I quickly whipped up support for UI Toolkit (by modifying the original DialogueUGUI).
Here is the UXML for an exemplary UI (sory, but this is the worst forum for posting code examples :(((
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
<ui:VisualElement style="flex-grow: 1;"> <ui:GroupBox name="dialogue_box" style="width: 50%; background-color: rgba(0, 0, 0, 0.59); border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); border-top-width: 2px; border-right-width: 2px; border-bottom-width: 2px; border-left-width: 2px; border-top-left-radius: 8px; border-top-right-radius: 8px; border-bottom-right-radius: 8px; border-bottom-left-radius: 8px; padding-top: 8px; padding-right: 8px; padding-bottom: 8px; padding-left: 8px; margin-top: 16px; margin-right: 16px; margin-bottom: 16px; margin-left: 16px; display: flex;"> <ui:VisualElement name="InfoGroup" style="min-height: auto; flex-direction: row; width: initial; min-width: auto; align-items: flex-start; margin-bottom: 8px;"> <ui:Image name="info_image" style="width: 100%; flex-shrink: 0; --unity-image: url('project://database/Assets/UI/CowboyAvatar.jpg?fileID=21300000&guid=0bfbcc7a51ecf47c3ac5d0c6c468a5f9&type=3#CowboyAvatar'); flex-basis: 64px;" /> <ui:VisualElement style="flex-grow: 1; padding-left: 8px;"> <ui:Label tabindex="-1" text="Label" parse-escape-sequences="true" display-tooltip-when-elided="true" name="info_name" style="margin-top: 0; margin-right: 0; margin-bottom: 8px; margin-left: 0; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; background-color: rgba(255, 255, 255, 0); color: rgb(255, 255, 255); -unity-font-style: bold; -unity-font: url('project://database/Assets/UI/Fonts/GOTHMBOL.TTF?fileID=12800000&guid=9224a44a0540b4c218d2a1780dfcf0cf&type=3#GOTHMBOL');" /> <ui:Label tabindex="-1" text="Actor Text" parse-escape-sequences="true" display-tooltip-when-elided="true" name="info_label" style="-unity-font: url('project://database/Assets/UI/Fonts/GOTHMBOK.TTF?fileID=12800000&guid=12981ab2246574a2fa52f10f8fe03d3e&type=3#GOTHMBOK'); color: rgb(255, 255, 255); padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; white-space: normal; font-size: 12px;" /> <ui:Label tabindex="-1" text="..." parse-escape-sequences="true" display-tooltip-when-elided="true" name="info_continue" style="align-self: flex-end; border-left-color: rgb(255, 255, 255); border-right-color: rgb(255, 255, 255); border-top-color: rgb(255, 255, 255); border-bottom-color: rgb(255, 255, 255); color: rgb(255, 255, 255); margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0;" /> </ui:VisualElement> </ui:VisualElement> <ui:VisualElement name="question_group" style="flex-grow: 1;"> <ui:Button text="Option 1" parse-escape-sequences="true" display-tooltip-when-elided="true" name="dialogue_button" class="option-button" /> </ui:VisualElement> </ui:GroupBox> </ui:VisualElement> <strong>Here is the code:</strong> using UnityEngine; using UnityEngine.UIElements; using System.Collections; using System.Collections.Generic; using System.Linq; using NodeCanvas.DialogueTrees; using UnityEngine.EventSystems; namespace XCanvas { public class DialogueUGUI : MonoBehaviour, IPointerClickHandler { [System.Serializable] public class SubtitleDelays { public float characterDelay = 0.05f; public float sentenceDelay = 0.5f; public float commaDelay = 0.1f; public float finalDelay = 1.2f; } //Options... [Header("Input Options")] public bool skipOnInput; public bool waitForInput; //Group... [Header("Subtitles")] public UIDocument uiDocument; public string subtitlesGroupId; private VisualElement subtitlesGroup; public string actorSpeechId; private Label actorSpeech; public string actorNameId; private Label actorName; public string actorPortraitId; private Image actorPortrait; public string waitInputIndicatorId; private Label waitInputIndicator; public SubtitleDelays subtitleDelays = new SubtitleDelays(); public List typingSounds; private AudioSource playSource; //Group... [Header("Multiple Choice")] public string optionsGroupId; private VisualElement optionsGroup; public string optionButtonId; public Button optionButton; private Dictionary<Button, int> cachedButtons; private Vector2 originalSubsPosition; private bool isWaitingChoice; private AudioSource _localSource; private AudioSource localSource { get { return _localSource != null ? _localSource : _localSource = gameObject.AddComponent(); } } private bool anyKeyDown; public void OnPointerClick(PointerEventData eventData) => anyKeyDown = true; void LateUpdate() => anyKeyDown = false; void Awake() { FindComponents(); Subscribe(); Hide(); } void OnEnable() { UnSubscribe(); Subscribe(); } void OnDisable() { UnSubscribe(); } void FindComponents() { var rootVisualElement = uiDocument.rootVisualElement; subtitlesGroup = rootVisualElement.Q(subtitlesGroupId); actorSpeech = rootVisualElement.Q<label>(actorSpeechId); actorName = rootVisualElement.Q<label>(actorNameId); actorPortrait = rootVisualElement.Q(actorPortraitId); waitInputIndicator = rootVisualElement.Q<label>(waitInputIndicatorId); optionsGroup = rootVisualElement.Q(optionsGroupId); optionButton = rootVisualElement.Q<button>(optionButtonId); }</button></label></label></label> void Subscribe() { DialogueTree.OnDialogueStarted += OnDialogueStarted; DialogueTree.OnDialoguePaused += OnDialoguePaused; DialogueTree.OnDialogueFinished += OnDialogueFinished; DialogueTree.OnSubtitlesRequest += OnSubtitlesRequest; DialogueTree.OnMultipleChoiceRequest += OnMultipleChoiceRequest; } void UnSubscribe() { DialogueTree.OnDialogueStarted -= OnDialogueStarted; DialogueTree.OnDialoguePaused -= OnDialoguePaused; DialogueTree.OnDialogueFinished -= OnDialogueFinished; DialogueTree.OnSubtitlesRequest -= OnSubtitlesRequest; DialogueTree.OnMultipleChoiceRequest -= OnMultipleChoiceRequest; } void Hide() { subtitlesGroup.style.display = DisplayStyle.None; optionsGroup.style.display = DisplayStyle.None; optionButton.style.display = DisplayStyle.None; waitInputIndicator.style.display = DisplayStyle.None; originalSubsPosition = subtitlesGroup.transform.position; } void OnDialogueStarted(DialogueTree dlg) { //nothing special... } void OnDialoguePaused(DialogueTree dlg) { subtitlesGroup.style.display = DisplayStyle.None; optionsGroup.style.display = DisplayStyle.None; StopAllCoroutines(); if ( playSource != null ) playSource.Stop(); } void OnDialogueFinished(DialogueTree dlg) { subtitlesGroup.style.display = DisplayStyle.None; optionsGroup.style.display = DisplayStyle.None; if ( cachedButtons != null ) { foreach ( var tempBtn in cachedButtons.Keys ) { if ( tempBtn != null ) { tempBtn.RemoveFromHierarchy(); } } cachedButtons = null; } StopAllCoroutines(); if ( playSource != null ) playSource.Stop(); } ///---------------------------------------------------------------------------------------------- void OnSubtitlesRequest(SubtitlesRequestInfo info) { StartCoroutine(Internal_OnSubtitlesRequestInfo(info)); } IEnumerator Internal_OnSubtitlesRequestInfo(SubtitlesRequestInfo info) { var text = info.statement.text; var audio = info.statement.audio; var actor = info.actor; subtitlesGroup.style.display = DisplayStyle.Flex; // subtitlesGroup.position = originalSubsPosition; actorSpeech.text = ""; actorName.text = actor.name; actorSpeech.style.color = actor.dialogueColor; if (actor.portraitSprite != null) { actorPortrait.style.display = DisplayStyle.Flex; } actorPortrait.sprite = actor.portraitSprite; if ( audio != null ) { var actorSource = actor.transform != null ? actor.transform.GetComponent() : null; playSource = actorSource != null ? actorSource : localSource; playSource.clip = audio; playSource.Play(); actorSpeech.text = text; var timer = 0f; while ( timer < audio.length ) { if ( skipOnInput && anyKeyDown ) { playSource.Stop(); break; } timer += Time.deltaTime; yield return null; } } if ( audio == null ) { var tempText = ""; var inputDown = false; if ( skipOnInput ) { StartCoroutine(CheckInput(() => { inputDown = true; })); } for ( int i = 0; i < text.Length; i++ ) { if ( skipOnInput && inputDown ) { actorSpeech.text = text; yield return null; break; } if ( subtitlesGroup.style.display == DisplayStyle.None ) { yield break; } char c = text<em class="d4pbbc-italic"></em>; tempText += c; yield return StartCoroutine(DelayPrint(subtitleDelays.characterDelay)); PlayTypeSound(); if ( c == '.' || c == '!' || c == '?' ) { yield return StartCoroutine(DelayPrint(subtitleDelays.sentenceDelay)); PlayTypeSound(); } if ( c == ',' ) { yield return StartCoroutine(DelayPrint(subtitleDelays.commaDelay)); PlayTypeSound(); } actorSpeech.text = tempText; } if ( !waitForInput ) { yield return StartCoroutine(DelayPrint(subtitleDelays.finalDelay)); } } if ( waitForInput ) { waitInputIndicator.style.display = DisplayStyle.Flex; while ( !anyKeyDown ) { yield return null; } waitInputIndicator.style.display = DisplayStyle.None; } yield return null; subtitlesGroup.style.display = DisplayStyle.None; info.Continue(); } void PlayTypeSound() { if ( typingSounds.Count > 0 ) { var sound = typingSounds[Random.Range(0, typingSounds.Count)]; if ( sound != null ) { localSource.PlayOneShot(sound, Random.Range(0.6f, 1f)); } } } IEnumerator CheckInput(System.Action Do) { while ( !anyKeyDown ) { yield return null; } Do(); } IEnumerator DelayPrint(float time) { var timer = 0f; while ( timer < time ) { timer += Time.deltaTime; yield return null; } } ///---------------------------------------------------------------------------------------------- void OnMultipleChoiceRequest(MultipleChoiceRequestInfo info) { optionsGroup.style.display = DisplayStyle.Flex; cachedButtons = new Dictionary<Button, int>(); int i = 0; foreach ( KeyValuePair<IStatement, int> pair in info.options ) { var button = new Button(); button.name = "button_" + pair.Value; button.text = pair.Key.text; button.ClearClassList(); foreach (var cls in optionButton.GetClasses()) { button.AddToClassList(cls); } optionsGroup.Add(button); // button. = optionButton.style; // var btn = (Button) Instantiate(optionButton); // btn.gameObject.SetActive(true); // btn.transform.SetParent(optionsGroup.transform, false); // btn.transform.localPosition = (Vector3)optionButton.transform.localPosition - new Vector3(0, buttonHeight * i, 0); // btn.GetComponentInChildren().text = pair.Key.text; cachedButtons.Add(button, pair.Value); button.RegisterCallback((evt) => { Finalize(info, cachedButtons); }); // button.clicked += () => { Finalize(info, cachedButtons); }; // btn.onClick.AddListener(() => { Finalize(info, cachedButtons[btn]); }); i++; } if ( info.showLastStatement ) { subtitlesGroup.style.display = DisplayStyle.Flex; // .gameObject.SetActive(true); // var newY = optionsGroup.position.y + optionsGroup.sizeDelta.y + 1; // subtitlesGroup.position = new Vector3(subtitlesGroup.position.x, newY, subtitlesGroup.position.z); } if ( info.availableTime > 0 ) { StartCoroutine(CountDown(info)); } } IEnumerator CountDown(MultipleChoiceRequestInfo info) { isWaitingChoice = true; var timer = 0f; while ( timer < info.availableTime ) { if ( isWaitingChoice == false ) { yield break; } timer += Time.deltaTime; SetMassAlpha(optionsGroup, Mathf.Lerp(1, 0, timer / info.availableTime)); yield return null; } if ( isWaitingChoice ) { Finalize(info, info.options.Values.Last()); } } void Finalize(MultipleChoiceRequestInfo info, int index) { isWaitingChoice = false; SetMassAlpha(optionsGroup, 1f); optionsGroup.style.display = DisplayStyle.None; subtitlesGroup.style.display = DisplayStyle.None; foreach ( var tempBtn in cachedButtons.Keys ) { tempBtn.RemoveFromHierarchy(); // Destroy(tempBtn.gameObject); } info.SelectOption(index); } void SetMassAlpha(VisualElement root, float alpha) { foreach ( var graphic in gameObject.GetComponentsInChildren() ) { graphic.SetAlpha(alpha); } } } } |
Hello again.
Thank you. I will check this out.
I also removed the “fancy” editor from the forum so that now there is a “CODE” block that you can put the code inside and which code is formated correctly (this was always there and possible by putting code within quotes `, but it was not apparent, sorry).
1 2 3 4 5 |
void SomeCode(string message) { Debug.Log(message); } |
Join us on Discord: https://discord.gg/97q2Rjh