【问题标题】:Executing Yield return stops the Coroutine in Unity [closed]执行 Yield return 会停止 Unity 中的协程 [关闭]
【发布时间】:2020-01-15 11:19:01
【问题描述】:

当我使用yield return null; 或任何其他返回类型时,我的协程结束。我有for 循环以间隔打印所有字母,但是当我执行yield return IEnumerator 协程结束时

但如果没有yield,它可以正常工作。

这里是代码

    public Text text;
    Animation anim;
    public Coroutine cor = null;
    private bool corR = false;
    public float timing = 0.0f;

    public void ChangeText(string txt)
    {
        if (cor != null)
        {
            StopCoroutine(cor);
            cor = null;
        }

        cor = StartCoroutine(__change(timing, txt));
    }

    IEnumerator __change(float time, string txt)
    {
        text.text = "";
        for(int i = 0; i < txt.Length; i++)
        {
            text.text += txt[i];

            yield return new WaitForSeconds(time);
        }


        corR = false;
    }```

【问题讨论】:

  • 你是如何开始你的协程的?
  • 这里是启动协程的函数。 public void ChangeText(string txt) { if (cor != null) { StopCoroutine(cor);心=空; } cor = StartCoroutine(__change(timing, txt)); }
  • ...当你说协程“结束”时——你的意思是它返回了吗?如果是这样,那是意料之中的。你的意思是for 循环的下一次迭代永远不会执行,即使在等待time 秒之后?
  • 是的,在yield return循环之后再也没有执行过,这就是问题所在。
  • 您是否尝试过将timing 设置为高于0.0 的值?

标签: c# unity3d coroutine


【解决方案1】:

代码本身看起来不错,如果没有其他任何东西干扰这个脚本(比如禁用它等)对我来说听起来你的 Time.timescale0

WaitForSeconds 依赖于Time.timescale

实际暂停时间等于给定时间除以Time.timescale。如果您希望使用 unscaled 时间等待,请参阅 WaitForSecondsRealtimeWaitForSeconds 只能与协程中的 yield 语句一起使用。

因此,如果是这种情况,您宁愿使用WaitForSecondsRealtime

IEnumerator __change(float time, string txt)
{
    // you might probably also want to set this in the beginning
    corR = true;

    text.text = "";
    for(int i = 0; i < txt.Length; i++)
    {
        text.text += txt[i];

        yield return new WaitForSecondsRealtime(time);
    }

    corR = false;
}

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 2019-01-04
    • 2019-06-19
    • 2018-04-18
    • 1970-01-01
    • 2021-11-27
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多