Skip to content

Instantly share code, notes, and snippets.

@krukru
Last active October 20, 2022 13:15
Show Gist options
  • Save krukru/98a81fe29b4719f62376f71f92e6cf4b to your computer and use it in GitHub Desktop.
Save krukru/98a81fe29b4719f62376f71f92e6cf4b to your computer and use it in GitHub Desktop.
Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogueSystem : MonoBehaviour
{
public ProgressiveText dialogueText;
public static DialogueSystem Instance { get; set; }
public GameObject dialoguePanel;
public string npcName;
public List<string> dialogueLines = new List<string>();
Button continueButton;
Text nameText;
int dialogueIndex;
private void Awake()
{
dialoguePanel.SetActive(false);
continueButton = dialoguePanel.transform.Find("Continue").GetComponent<Button>();
nameText = dialoguePanel.transform.Find("Name").GetChild(0).GetComponent<Text>();
continueButton.onClick.AddListener(delegate { ContinueDialogue(); });
dialoguePanel.SetActive(false);
if(Instance != null && Instance != this)
{
Destroy(gameObject);
}
else
{
Instance = this;
}
}
public void AddNewDialogue(string[] lines, string npcName)
{
dialogueIndex = 0;
dialogueLines = new List<string>(lines.Length);
dialogueLines.AddRange(lines);
this.npcName = npcName;
Debug.Log(dialogueLines.Count);
CreateDialogue();
}
public void CreateDialogue()
{
dialoguePanel.SetActive(true);
dialogueText.ShowText(dialogueLines[0]);
nameText.text = npcName;
}
public void ContinueDialogue()
{
if(dialogueIndex < dialogueLines.Count-1)
{
dialogueIndex++;
dialogueText.ShowText(dialogueLines[dialogueIndex]);
}
else
{
dialoguePanel.SetActive(false);
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class ProgressiveText : MonoBehaviour
{
public float pause = 1.0f;
private string _message = String.Empty;
private Text _textUI;
private IEnumerator activeCoroutine;
private int index;
private void Awake()
{
_textUI = GetComponent<Text>();
activeCoroutine = InternalShowText();
}
public void ShowText(string text)
{
_message = text;
_textUI.text = "";
StopCoroutine(activeCoroutine);
index = 1;
StartCoroutine(activeCoroutine);
}
private IEnumerator InternalShowText()
{
for (; index <= _message.Length; index++)
{
_textUI.text = _message.Substring(0, index);
yield return new WaitForSeconds(pause);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment