Skip to content

Instantly share code, notes, and snippets.

@SiarheiPilat
Created January 23, 2023 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SiarheiPilat/664d16a92174625b9b3d606528562323 to your computer and use it in GitHub Desktop.
Save SiarheiPilat/664d16a92174625b9b3d606528562323 to your computer and use it in GitHub Desktop.
Simple UI script for NodeCanvas dialogue tree.
using System.Collections.Generic;
using UnityEngine;
using NodeCanvas.DialogueTrees;
using TMPro;
using UnityEngine.UI;
using NodeCanvas.Framework;
public class NcSimpleDialogueUi : MonoBehaviour
{
public TextMeshProUGUI NarrationText;
public Button AnswerButtonPrefab; // NOTE: NOT a scene object!!
public Transform ButtonsParent;
public DialogueTreeController DialogueTreeController;
//public Blackboard Blackboard; // uncomment if you want to use variables, e.g. List<Variable> results = Blackboard.GetVariables().ToList();
#region SETUP
private void Awake()
{
DialogueTree.OnDialogueStarted += OnDialogueStarted;
DialogueTree.OnSubtitlesRequest += OnSubtitlesRequest;
DialogueTree.OnDialogueFinished += OnDialogueFinished;
DialogueTree.OnMultipleChoiceRequest += OnMultipleChoiceRequest;
}
void OnDisable() { UnSubscribe(); }
void UnSubscribe()
{
DialogueTree.OnDialogueStarted -= OnDialogueStarted;
DialogueTree.OnDialogueFinished -= OnDialogueFinished;
DialogueTree.OnSubtitlesRequest -= OnSubtitlesRequest;
DialogueTree.OnMultipleChoiceRequest -= OnMultipleChoiceRequest;
}
#endregion
private void Start()
{
DialogueTreeController.StartDialogue();
}
void OnDialogueStarted(DialogueTree dlg)
{
//print("started");
}
void OnSubtitlesRequest(SubtitlesRequestInfo info)
{
NarrationText.text = info.statement.text;
info.Continue();
}
void OnMultipleChoiceRequest(MultipleChoiceRequestInfo info)
{
//print("mult choice request");
if (ButtonsParent)
{
for (int i = 0; i < ButtonsParent.childCount; i++)
{
Destroy(ButtonsParent.transform.GetChild(i).gameObject);
}
}
foreach (KeyValuePair<IStatement, int> pair in info.options)
{
Button btn = Instantiate(AnswerButtonPrefab, ButtonsParent);
btn.GetComponentInChildren<TextMeshProUGUI>().text = pair.Key.text;
btn.onClick.AddListener(() => { SelectOption(info, pair.Value); });
}
}
private void SelectOption(MultipleChoiceRequestInfo info, int index)
{
info.SelectOption(index);
}
void OnDialogueFinished(DialogueTree dlg)
{
//print("finished");
if (ButtonsParent)
{
for (int i = 0; i < ButtonsParent.childCount; i++)
{
Destroy(ButtonsParent.transform.GetChild(i).gameObject);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment