Home > Mobile >  Typewriter effect that shows one character per click on a button in Unity C#
Typewriter effect that shows one character per click on a button in Unity C#

Time:04-17

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;
        }
    }
}

CodePudding user response:

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);
    }
}
  • Related