【问题标题】:Co-routine Wrapper not executing callback in a timely manner协程 Wrapper 没有及时执行回调
【发布时间】:2014-10-15 07:15:06
【问题描述】:

好的,所以我对如何在 Unity3d 中使用协同程序有了一个很好的了解 但我想为延迟执行制作一个可重用的组件,让我能够 取这样的代码

StartCoroutine(WaitForDamageCooldown(DamageCooldown));

IEnumerator WaitForDamageCooldown(float duration)
{
    yield return new WaitForSeconds(duration);
    HasTempInvincibility = false;
}

把它转换成这样的东西

CoroutineUtil.DeferredExecutor(float waitTime,Action onComplete);

这样使用

StartCoroutine(CoroutineUtil.DeferredExecutor(WaitTime, () =>
{
    Debug.Log("DeferredExecutor wait complete");
    HasTempInvincibility = false;
}));

我已经尝试在下面实现它

using System;
using System.Collections;
using UnityEngine;

public static class CoroutineUtil
{
    public static IEnumerator DeferredExecutor(float waitDuration, Action onComplete)
    {
        yield return new WaitForSeconds(waitDuration);
        onComplete.Invoke();
    }

    public static IEnumerator DeferredExecutor<T>(float waitDuration, T obj, Action<T> onComplete)
    {
        yield return new WaitForSeconds(waitDuration);
        onComplete.Invoke(obj);
    }
}

认为这可能不能作为静态工作,我也尝试将它添加到对象的类中

public class Player: MonoBehaviour
{
///....etc
    IEnumerator DeferredExecutor(float waitDuration, Action onComplete)
    {
        yield return new WaitForSeconds(waitDuration);
        onComplete.Invoke();
    }

///....etc
}

结果是零星的。我无法确定协同程序何时完成的押韵或原因,但它在预期的时间后运行良好。

我的方法有问题吗

【问题讨论】:

  • 代码应该没问题。我在我的代码中使用了非常相似的东西并且工作得很好。唯一不同的是基本上您明确调用 Invoke:您是否尝试过简短形式并查看它是否有效? es。 onComplete();
  • 谢谢,我会试一试...伟大的思想和我猜想的一样...
  • 让我知道我对此感兴趣。
  • 好吧,事实证明,在其他代码中,当我使用它来实现减速效果时,我的游戏时间被缩短了。它确实有效!
  • 很高兴知道,否则会很奇怪。

标签: c# unity3d coroutine


【解决方案1】:

这确实有效,但与 Unity3d 中的其他协程一样,它反映了来自 Time.TimeScale 的时间。所以因为那 2 秒不一定是 2 秒。(这是我的问题)

Time.TimesScale = 1.0f;

话虽如此,以下是我一直在实施的方式。

public static IEnumerator DeferredExecutor(float waitDuration, Action onComplete)
{
  yield return new WaitForSeconds(waitDuration);
  onComplete();
}

这就是我一直在使用它的方式。

StartCoroutine(CoroutineUtil.DeferredExecutor(2f, () =>
{
  _TimePause.OnPause();
  GameOverCanvas.enabled = true;
}));

这确实有效,但请确保您记住正确的调用约定。具体来说 StartRoutine

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多