【发布时间】:2018-12-07 22:51:44
【问题描述】:
我有 2 个 IEnumerator 协程,它们非常相似,应该将它们组合起来:
答:
IEnumerator CountDown_A() {
timeLeft_A = totalTime_A;
while (timeLeft_A > 0) {
yield return new WaitForSeconds(1);
timeLeft_A--;
}
}
乙:
IEnumerator CountDown_B() {
timeLeft_B = totalTime_B;
while (timeLeft_B > 0) {
yield return new WaitForSeconds(1);
timeLeft_B--;
}
}
唯一的两个区别是变量totalTime_A vs totalTime_B 和timeLeft_A vs timeLeft_B。这些变量来自此函数的范围之外。
我在模块化这个协程时遇到的问题是timeLeft_A 和timeLeft_B 的增量值需要应用到这个函数之外,所以我需要以某种方式传递对它们的引用。
用户“Kurt-Dekker”在this thread 中发布了一个很好的解决方案,但我无法将它应用到我的代码中。他说“使用闭包(函子)允许协程通过回调修改它”:
IEnumerator CountDown( System.Action<int> callback){
....
}
我认为应该这样称呼:
StartCoroutine ( CountDown( (i) => { timeLeft_A = i; } ) );
StartCoroutine ( CountDown( (i) => { timeLeft_B = i; } ) );
我不明白的是如何在 IEnumerator 内部引用/修改传入的 int 的实际值,如果我只需要使用回调函数的话。例如执行以下操作:
while(callback > 0){
或:
callback--;
任何帮助表示赞赏。
【问题讨论】:
-
我不太明白你在问什么......你需要将参数传递给你的协程吗?
-
好吧,经过第二次阅读,我现在明白了 :) 倒计时变量是在协程之外修改的,对吧?
-
是的,我基本上需要通过引用将
timeLeft_A传递给CountDown_A()(值需要全局更改)。 -
但我希望
CountDown_A()和CountDown_B()具有相同的功能,所以也许CountDown()。所以全局变量不能在里面显式命名。 -
好吧,没关系..我会尽力为你找到解决方案:)
标签: c# unity3d closures functor coroutine