Last active
April 11, 2024 08:11
-
-
Save unitycoder/19625fed364a39cb278f to your computer and use it in GitHub Desktop.
Type out UI text one character at a time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using UnityEngine.UI; | |
// attach to UI Text component (with the full text already there) | |
public class UITextTypeWriter.cs : MonoBehaviour | |
{ | |
Text txt; | |
string story; | |
void Awake () | |
{ | |
txt = GetComponent<Text> (); | |
story = txt.text; | |
txt.text = ""; | |
// TODO: add optional delay when to start | |
StartCoroutine (PlayText()); | |
} | |
IEnumerator PlayText() | |
{ | |
foreach (char c in story) | |
{ | |
txt.text += c; | |
yield return new WaitForSeconds (0.125f); | |
} | |
} | |
} |
Here is a simplier approach, without audio
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(TextMeshProUGUI))]
public class ScrollText : MonoBehaviour
{
public string GameSceneName;
public float InitialDelay = 0.1f;
public float CharWait = 0.5f;
public float CommaWait = 0.3f;
public float PeriodWait = 0.5f;
TextMeshProUGUI textMesh;
string text;
// Start is called before the first frame update
void Start()
{
textMesh = GetComponent<TextMeshProUGUI>();
text = textMesh.text;
textMesh.text = "";
StartCoroutine(TypeText());
}
IEnumerator TypeText()
{
yield return new WaitForSeconds(InitialDelay);
foreach (char c in text)
{
textMesh.text += c;
yield return new WaitForSeconds(CharWait);
if (c == ',')
yield return new WaitForSeconds(CommaWait);
if (c == '.')
yield return new WaitForSeconds(PeriodWait);
}
SceneManager.LoadScene(GameSceneName);
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added an option to disable typing sound.
Also added a volume slider.