【问题标题】:unity c# using delegate chain with time delayunity c# 使用带时间延迟的委托链
【发布时间】:2018-12-25 23:08:10
【问题描述】:

我尝试使用如下委托链,尝试统一制作动画:

public class Class1
{
    class Dele {

        delegate void MyDelegate();
        private MyDelegate dele;

        private int count = 0;

        public void Animate() {
            dele = new MyDelegate(DoIe);
        }

        IEnumerator Ie() {
            Debug.Log(count);
            count += 1;
            yield return new WaitForSeconds(5f);
        }

        private void DoIe() {
            StartCouroutine(Ie());
            for (int i=0; i<10; i++) {
                dele += DoIe;
            }

            dele();
        }
    }

    //call new Dele().Animate() here
}

我认为日志会像 1 (5 秒) 2 (5 秒) ... 10

但是, 1 2 .. 10 被同时记录。

如果我想在 5 秒后回调另一个 Ie, 我该怎么办??

【问题讨论】:

标签: c# unity3d callback delegates


【解决方案1】:

对于协程,它是稍后运行的例程(IEnumerator 方法)内部的代码。上面的 void-returning 方法中的代码 after StartCoroutine() 将运行 synchronously(直接),就像你看到的那样。

这里根本不需要委托。你只需要这个:

IEnumerator Ie() {
    for (int i=0; i<10; i++) {
        Debug.Log(count);
        count += 1;
        yield return new WaitForSeconds(5f);
    }
}

private void DoIe() {
    StartCoroutine(Ie());
}

【讨论】:

    【解决方案2】:

    首先,您的类需要继承 MonoBehavious 才能使 StartCoroutine 工作。 然后关于您的问题:您需要延迟启动协程,只是将它们添加到多播委托中根本没有按照您的想法进行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多