-
Notifications
You must be signed in to change notification settings - Fork 3
/
Typer.cs
81 lines (72 loc) · 2.09 KB
/
Typer.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
[Serializable]
public class TyperMessage
{
public string Text;
public float Duration;
public TyperMessage(string text, float duration)
{
Text = text;
Duration = duration;
}
}
[RequireComponent (typeof (Text))]
public class Typer : MonoBehaviour
{
public List<TyperMessage> Messages;
private Text _display;
private TyperMessage _currentMessage;
private float _timeMessageStarted;
private float _timeLastTyped;
private int _currentProgress;
private float _typeDelay = .05f;
private const float AverageTypeDelay = .05f;
void Start()
{
_display = GetComponent<Text>();
}
void Update () {
if (_currentMessage == null)
{
if (Messages.Count > 0)
{
_currentMessage = Messages[0];
Messages.Remove(_currentMessage);
_timeMessageStarted = Time.time;
_currentProgress = 0;
}
else
{
return;
}
}
if (_currentProgress <= _currentMessage.Text.Length)
{
if (!(Time.time > _timeLastTyped + _typeDelay)) return;
TypeNextCharacter(_currentMessage, _currentProgress);
_currentProgress++;
_timeLastTyped = Time.time;
_typeDelay = AverageTypeDelay * (.5f + UnityEngine.Random.value);
}
else
{
if (!(Time.time > _timeMessageStarted + _currentMessage.Duration)) return;
_currentMessage = null;
_display.text = "";
}
}
private void TypeNextCharacter(TyperMessage currentMessage, int currentProgress)
{
var sb = new StringBuilder();
sb.Append(currentMessage.Text.Substring(0, currentProgress));
sb.Append("<color=#ffffff00>");
sb.Append(currentMessage.Text.Substring(currentProgress));
sb.Append("</color>");
_display.text = sb.ToString();
}
}