【问题标题】:Unity: Fast-Forward Type Writer Effect upon KeypressUnity:按键时的快进类型编写器效果
【发布时间】:2021-08-18 18:40:37
【问题描述】:

对于 2D 平台游戏的过场动画,我编写了一个脚本,显示文本就像是打字机写的一样。由于文本可能很长,我想为用户实现一个选项来快进/跳过动画并在按键时显示全文。这就是我现在拥有的:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TypeWriter : MonoBehaviour
{
    public float delay = 0.05f;
    public string fullText;
    private string currentText = "";

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(ShowText());
    }

    IEnumerator ShowText()
    {
        for (int i = 0; i < fullText.Length + 1; i++)
        {
            currentText = fullText.Substring(0, i);
            this.GetComponent<Text>().text = currentText;
            yield return new WaitForSeconds(delay);
        }
    }
}

有人可以帮帮我吗?我是 Unity 和 C# 的新手。

【问题讨论】:

  • 可以添加ScrollBar UI组件来显示长文本。
  • 只需在协程中放置一个标志,在设置标志时不会产生等待。如果设置了该标志,则整个循环将用完并且不会有任何收益,因此不再等待。在按键上触发标志。
  • @Charleh 感谢您的回复!你说的国旗是什么意思?你可以在代码中显示它吗?我没有使用 Unity 或 C# 的经验,抱歉!
  • 基本上是一个布尔值。真假。如果将其设置为 true,则跳过产量。如果您是编程新手,我建议您参加初学者课程,这样您会学得更快。

标签: c# unity3d coroutine ienumerator


【解决方案1】:

设置标志应该可以解决问题:

    bool skip = false;

    IEnumerator ShowText()
    {
        for (int i = 0; i < fullText.Length + 1; i++)
        {
            currentText = fullText.Substring(0, i);
            this.GetComponent<Text>().text = currentText;
            if (!skip)
              yield return new WaitForSeconds(delay);
        }
    }

只需在某个点将skip 设置为true,这将导致循环不产生,这将导致循环完全完成(一个小的优化是在设置跳过标志时不循环,只是而是用剩余的字母填充文本,但我怀疑即使使用循环,您也会遇到性能问题,因为它是如此简单)。

您可以根据接收到的按键/某些输入将标志设置为 true。

【讨论】:

    猜你喜欢
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    相关资源
    最近更新 更多