'Typewriter effect that shows one character per click on a button in Unity C#
I need help with creating a code for a typewriter effect that only displays one character per click(ui button), I'm really new to Unity and coding as a whole, and I used a tutorial to use the typewriter effect, then i tried to make it so it only works as one character per click on the button, but it didn't work.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TypeWriterEffect : MonoBehaviour {
public float delay = 0.1f;
public string fullText;
private string currentText = "";
public Button toggleButton;
bool toggle = false;
void Start () {
toggleButton.onClick.AddListener(Toggle);
}
void Toggle()
{
StartCoroutine(ShowText());
toggle = true;
}
IEnumerator ShowText(){
if (toggle == true)
{
for (int i = 0; i < fullText.Length; i++)
{
this.GetComponent<Text>().text = currentText;
currentText = fullText.Substring(0, i);
yield return new WaitForSeconds(delay);
}
toggle = false;
}
}
}
Solution 1:[1]
If you really want it to only display one character per click on a UI button, you can cut it down to something like this:
using UnityEngine;
using UnityEngine.UI;
public class TypeWriterEffect : MonoBehaviour
{
public string fullText;
public Button toggleButton;
public int carriage=0;
void Start () {
toggleButton.onClick.AddListener(Clicked);
GetComponent<Text>().text = fullText.Substring(0, carriage);
}
void Clicked()
{
carriage++;
GetComponent<Text>().text = fullText.Substring(0, carriage);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |