Skip to content

Instantly share code, notes, and snippets.

@Estecka
Created June 28, 2019 10:19
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 Estecka/633d87452f4430208795b34722a9e05a to your computer and use it in GitHub Desktop.
Save Estecka/633d87452f4430208795b34722a9e05a to your computer and use it in GitHub Desktop.
Write/erase a text one caracter after another.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using TMPro;
public class Typewriter : MonoBehaviour {
static readonly string format = @"{0}<alpha=#00>{1}</color>{2}";
public bool playOnAwake = false;
public bool clearOnAwake = false;
[Space]
public float frequency = 10;
public float delay = 0.25f;
public TextMeshProUGUI textIn;
public TextMeshProUGUI textOut;
public UnityEvent onTypingFinished;
void Start(){
if (playOnAwake)
this.SetText(textIn.text);
else if (clearOnAwake)
textIn.text = string.Empty;
if (textOut && clearOnAwake)
textOut.text = string.Empty;
}
public void SetText(string newText){
this.StartCoroutine(Erase(textIn.text));
textIn.text = string.Empty;
this.StartCoroutine(Write(newText, delay));
}
IEnumerator Write(string message, float delay){
yield return new WaitForSeconds(delay);
for (int i=1; i<=message.Length; i++){
int invisibleLength = message.Length - i;
string visible = message.Substring(0, i);
string invisible = message.Substring(i, invisibleLength);
textIn.text = string.Format(format, visible, invisible, null);
yield return new WaitForSeconds(1/frequency);
}
textIn.text = message;
onTypingFinished.Invoke();
}
IEnumerator Erase(string message){
if (!textOut)
yield break;
for (int i=1; i<=message.Length; i++){
int visibleLength = message.Length - i;
string invisible = message.Substring(0, i);
string visible = message.Substring(i, visibleLength);
textOut.text = string.Format(format, null, invisible, visible);
yield return new WaitForSeconds(1/frequency);
}
textOut.text = string.Empty;
}
}
fileFormatVersion: 2
guid: 84574759eaaf5dd48a7e1a1953850767
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 3823979315032016401, guid: 0000000000000000d000000000000000, type: 0}
userData:
assetBundleName:
assetBundleVariant:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment