c# - 协程Wrapper没有及时执行回调

标签 c# unity3d coroutine

好的,我对如何在 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
}

结果是零星的。我想不出协程何时完成的押韵或理由,但它在预期时间后完成得很好。

我的做法有问题吗

最佳答案

这确实有效,但与 Unity3d 中的其他协程一样,它反射(reflect)了来自 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;
}));

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

关于c# - 协程Wrapper没有及时执行回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25429980/

相关文章:

python - 如何在同步环境中执行 Tornado 协程?

c# - C#/.NET 3.5 的文件存储数据库?

c# - 如何正确地将浮点指针从 C 库传递到其 C# 包装器

python - 在 python 中,有没有办法在调用函数之前检查函数是否为 "generator function"?

c# - 试图轻松保存游戏数据,需要帮助将对象统一添加到 json 文件

c# - 是否允许在另一个泛型方法中调用泛型方法?

java - Kotlin协程vs CompletableFuture

c# - 在没有模式的情况下解码 protobuf

C# DROPBOX API修改10000个文件限制

c# - 多少层太多了?