在 Unity C# 中每次单击按钮显示一个字符的打字机效果

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

我需要帮助创建打字机效果的代码,每次点击只显示一个字符(ui 按钮),我对 Unity 和整个编码真的很陌生,我使用了一个教程要使用打字机效果,然后我尝试将其设置为每次单击按钮仅作为一个字符使用,但它没有用。

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

如果您真的希望它在每次点击 UI 按钮时只显示一个字符,您可以将其缩减为如下内容:

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