SayAllenthing

Allen Devs - DialogueWindow

Oct 4th, 2020
1,666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. //Created by Allen Devs 2020, free to use in your game, don't sweat it, enjoy!
  2.  
  3. using System.Collections;
  4. using UnityEngine;
  5. using TMPro;
  6.  
  7. public class DialogueWindow : MonoBehaviour
  8. {
  9.     const string kAlphaCode = "<color=#00000000>";
  10.     const float kMaxTextTime = 0.1f;
  11.     public static int TextSpeed = 2;
  12.  
  13.     public TMP_Text Text;
  14.     private string CurrentText;
  15.  
  16.     Animator Anim;
  17.  
  18.     void Start()
  19.     {
  20.         Anim = GetComponent<Animator>();
  21.         if (Anim == null)
  22.         {
  23.             Debug.LogError("No Animator Controller on DialogueWindow: " + gameObject.name);
  24.         }
  25.     }
  26.  
  27.     public void Show(string text)
  28.     {
  29.         Anim?.SetBool("Open", true);
  30.         CurrentText = text;      
  31.     }
  32.  
  33.     public void Close()
  34.     {        
  35.         Anim?.SetBool("Open", false);
  36.     }
  37.  
  38.     public void OnDialogueOpen()
  39.     {
  40.         StartCoroutine(DisplayText());
  41.     }
  42.  
  43.     public void OnDialogueClosed()
  44.     {
  45.         StopAllCoroutines();
  46.         Text.text = "";
  47.     }
  48.  
  49.     private IEnumerator DisplayText()
  50.     {
  51.         if (Text == null)
  52.         {
  53.             Debug.LogError("Text is not linked in DialogueWindow: " + gameObject.name);
  54.             yield return null;
  55.         }
  56.  
  57.         Text.text = "";
  58.  
  59.         string originalText = CurrentText;
  60.         string displayedText = "";
  61.         int alphaIndex = 0;
  62.  
  63.         foreach(char c in CurrentText.ToCharArray())
  64.         {
  65.             alphaIndex++;
  66.             Text.text = originalText;
  67.             displayedText = Text.text.Insert(alphaIndex, kAlphaCode);
  68.             Text.text = displayedText;
  69.  
  70.             yield return new WaitForSecondsRealtime(kMaxTextTime / TextSpeed);
  71.         }
  72.  
  73.         yield return null;
  74.     }
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment