C# 使用协程的循环
我对循环情况下的协同程序行为有一个疑问,请参见下面的代码提取作为Unity C#脚本上的示例: 状态机工作正常,但当前状态为Status1(C# 使用协程的循环,c#,unity3d,coroutine,C#,Unity3d,Coroutine,我对循环情况下的协同程序行为有一个疑问,请参见下面的代码提取作为Unity C#脚本上的示例: 状态机工作正常,但当前状态为Status1(StateTransitionCommand==false),由于State1()例程循环中的产生返回null,我原以为FMS()中的循环也会执行另一次生成调试日志“debug.log”(“State”+State);”的迭代 换句话说,我期望有很多调试日志(State1()例程的每个迭代都有一个,当状态为Status1时),但实际上,当状态为Status1
StateTransitionCommand==false
),由于State1()
例程循环中的产生返回null
,我原以为FMS()
中的循环也会执行另一次生成调试日志“debug.log”(“State”+State);”的迭代
换句话说,我期望有很多调试日志(State1()例程的每个迭代都有一个,当状态为Status1时),但实际上,当状态为Status1时,只执行1次
因此,我想我错过了一些关于收益功能的东西,有没有人能解释我这种行为?您的问题源于这样一个事实,即您的代码在
State1()
方法中没有中断,直到stateTransitionCommand==true
启动协同程序的方法,FSM()
,在State1
完成之前不会返回到。换言之,在协同路由完成之前,控制流不会返回到调用方法。我相信这是因为您在FSM
内部yield
-ingState1
(产生另一个协同程序)。显然,“普通”方法不会等到协同程序完成后才继续执行
请参阅下面的代码示例以了解示例:
using UnityEngine;
using System.Collections;
public class CoroutineTest : MonoBehaviour {
// current FSM state
public string state = "";
void Start()
{
StartCoroutine(FSM());
}
IEnumerator FSM()
{
state = "State1";
while (true)
{
Debug.Log("State: " + state);
// ExecuteOnce will execute exactly once before returning to the outer function
yield return StartCoroutine(ExecuteOnce());
// ExecuteIndefinitely will execute indefinitely until its while() loop is broken
// uncomment to test
//yield return StartCoroutine(ExecuteIndefinitely());
}
}
IEnumerator ExecuteOnce()
{
Debug.Log("Calling ExecuteOnce()");
yield return new WaitForSeconds(1f);
}
IEnumerator ExecuteIndefinitely()
{
Debug.Log("Calling ExecuteIndefinitely()");
while (true)
{
Debug.Log("Inside ExecuteIndefinitely()");
yield return new WaitForSeconds(1f);
}
}
}
unity标签用于Microsoft unity。不要误用它。
using UnityEngine;
using System.Collections;
public class CoroutineTest : MonoBehaviour {
// current FSM state
public string state = "";
void Start()
{
StartCoroutine(FSM());
}
IEnumerator FSM()
{
state = "State1";
while (true)
{
Debug.Log("State: " + state);
// ExecuteOnce will execute exactly once before returning to the outer function
yield return StartCoroutine(ExecuteOnce());
// ExecuteIndefinitely will execute indefinitely until its while() loop is broken
// uncomment to test
//yield return StartCoroutine(ExecuteIndefinitely());
}
}
IEnumerator ExecuteOnce()
{
Debug.Log("Calling ExecuteOnce()");
yield return new WaitForSeconds(1f);
}
IEnumerator ExecuteIndefinitely()
{
Debug.Log("Calling ExecuteIndefinitely()");
while (true)
{
Debug.Log("Inside ExecuteIndefinitely()");
yield return new WaitForSeconds(1f);
}
}
}