我对每次需要由协程完成的事情都有两个方法感到有点恼火。我需要协程和另一种方法来启动协程。也就是说,我需要一些代码仅在前一段代码完成时才执行。
我想通过启动一个匿名方法作为协程来解决它,但我发现它不起作用。关于如何避免因为需要协程而让你的类因额外的方法而变得臃肿,还有什么其他的技巧或诀窍吗?
发布于 2017-03-13 16:38:09
所以..。如果我理解正确的话,您希望代码执行一个启动协程的方法,但又不想用一个特定方法的1:1关系来启动每个特定的协程。
你不想在你的主代码中使用"StartCoroutine“吗?如果您想要避免代码膨胀,您可以这样做,这与three method解决方案类似,但使用相同的方法启动每个协程。
void Start()
{
_(DoThings("Hello"));
_(DoAnotherThing(" world!"));
}
void _(IEnumerator Method)
{
StartCoroutine(Method);
}
IEnumerator DoThings(string value)
{
yield return new WaitForSeconds(1);
Debug.Log(value);
}
IEnumerator DoAnotherThing(string value)
{
yield return new WaitForSeconds(1);
Debug.Log(value);
}发布于 2017-03-13 16:58:25
如果你想避免StartCoroutine把你的代码弄得乱七八糟,我会按照@Fredrik在他的回答中说明的那样做(这等同于使用StartCoroutine,但只是将它封装在一个不同的方法中)。这有助于保持方法的倒计时,即使您正在为一个可能从不继承MonoBehaviour且不能调用StartCoroutine的类调用的API执行此操作。
至于
,也就是说,我需要一些代码只有在前一段代码完成后才能执行。
我在协程中使用回调方法,如下所示:
IEnumerator Coroutine1(Action callback) {
// Contents of coroutine
callback();
}其用途如下:
StartCoroutine(Coroutine1(() => StartCoroutine(Coroutine2())));发布于 2017-03-13 14:44:17
在我的示例method_01中。
public void HandleMethod() {
StartCoroutine (Method_01 ());
}
private IEnumerator Method_01() {
var count = 5;
var wait1Second = new WaitForSeconds (1f); // wait
Debug.Log ("Start method 1");
while (count > 0) {
Debug.Log (count);
yield return wait1Second; // Each second
}
Debug.Log ("End method 1");
yield return null;
Debug.Log ("Start method 2");
yield return wait1Second;
Debug.Log ("End method 2");
}https://stackoverflow.com/questions/42757738
复制相似问题