-
Notifications
You must be signed in to change notification settings - Fork 10
/
typewriterUI.cs
90 lines (74 loc) · 2.08 KB
/
typewriterUI.cs
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
// Script for having a typewriter effect for UI
// Prepared by Nick Hwang (https://www.youtube.com/nickhwang)
// Want to get creative? Try a Unicode leading character(https://unicode-table.com/en/blocks/block-elements/)
// Copy Paste from page into Inpector
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class typewriterUI : MonoBehaviour
{
Text _text;
TMP_Text _tmpProText;
string writer;
[SerializeField] float delayBeforeStart = 0f;
[SerializeField] float timeBtwChars = 0.1f;
[SerializeField] string leadingChar = "";
[SerializeField] bool leadingCharBeforeDelay = false;
// Use this for initialization
void Start()
{
_text = GetComponent<Text>()!;
_tmpProText = GetComponent<TMP_Text>()!;
if(_text != null)
{
writer = _text.text;
_text.text = "";
StartCoroutine("TypeWriterText");
}
if (_tmpProText != null)
{
writer = _tmpProText.text;
_tmpProText.text = "";
StartCoroutine("TypeWriterTMP");
}
}
IEnumerator TypeWriterText()
{
_text.text = leadingCharBeforeDelay ? leadingChar : "";
yield return new WaitForSeconds(delayBeforeStart);
foreach (char c in writer)
{
if (_text.text.Length > 0)
{
_text.text = _text.text.Substring(0, _text.text.Length - leadingChar.Length);
}
_text.text += c;
_text.text += leadingChar;
yield return new WaitForSeconds(timeBtwChars);
}
if(leadingChar != "")
{
_text.text = _text.text.Substring(0, _text.text.Length - leadingChar.Length);
}
}
IEnumerator TypeWriterTMP()
{
_tmpProText.text = leadingCharBeforeDelay ? leadingChar : "";
yield return new WaitForSeconds(delayBeforeStart);
foreach (char c in writer)
{
if (_tmpProText.text.Length > 0)
{
_tmpProText.text = _tmpProText.text.Substring(0, _tmpProText.text.Length - leadingChar.Length);
}
_tmpProText.text += c;
_tmpProText.text += leadingChar;
yield return new WaitForSeconds(timeBtwChars);
}
if (leadingChar != "")
{
_tmpProText.text = _tmpProText.text.Substring(0, _tmpProText.text.Length - leadingChar.Length);
}
}
}