Unity 5.0.1 完全停止协程
Unity 5.0.1 Completely Stopping a Coroutine
好吧,所以我 运行 遇到了一个小问题,基本上,我有一个包含 for 循环的协程。我可以成功调用 StopCoroutine 和 StartCoroutine 方法,当然,这只是暂停和取消暂停协程。有没有办法真正停止并重新启动它?我的最终目标是能够启动协程,根据用户的判断终止它,并在任何时候从头重新启动它,也由用户自行决定。这是可以实现的吗?谢谢。
到"rewind"协程,只需用相同的参数再次调用协程方法即可。如果要保存这些参数,可以使用闭包:
public class CoroutineClosureExample : MonoBehaviour
{
private System.Func<IEnumerator> CreateCoroutineFactory(int someInt, float someFloat)
{
return () => CoroutineYouWant(someInt, someFloat);
}
private IEnumerator CoroutineYouWant(int someInt, float someFloat)
{
for(int i = 0; i < someInt; i++)
{
yield return new WaitForEndOfFrame();
}
}
private System.Func<IEnumerator> m_CurrentCoroutineFactory;
private IEnumerator m_CurrentCoroutine;
public void SetCoroutineParameters(int someInt, float someFloat)
{
m_CurrentCoroutineFactory = CreateCoroutineFactory(someInt, someFloat);
}
public void RestartCurrentCoroutine()
{
if (m_CurrentCoroutine != null)
{
StopCoroutine(m_CurrentCoroutine);
m_CurrentCoroutine = null;
}
if (m_CurrentCoroutineFactory != null)
{
m_CurrentCoroutine = m_CurrentCoroutineFactory();
StartCoroutine(m_CurrentCoroutine);
}
}
}
好吧,所以我 运行 遇到了一个小问题,基本上,我有一个包含 for 循环的协程。我可以成功调用 StopCoroutine 和 StartCoroutine 方法,当然,这只是暂停和取消暂停协程。有没有办法真正停止并重新启动它?我的最终目标是能够启动协程,根据用户的判断终止它,并在任何时候从头重新启动它,也由用户自行决定。这是可以实现的吗?谢谢。
到"rewind"协程,只需用相同的参数再次调用协程方法即可。如果要保存这些参数,可以使用闭包:
public class CoroutineClosureExample : MonoBehaviour
{
private System.Func<IEnumerator> CreateCoroutineFactory(int someInt, float someFloat)
{
return () => CoroutineYouWant(someInt, someFloat);
}
private IEnumerator CoroutineYouWant(int someInt, float someFloat)
{
for(int i = 0; i < someInt; i++)
{
yield return new WaitForEndOfFrame();
}
}
private System.Func<IEnumerator> m_CurrentCoroutineFactory;
private IEnumerator m_CurrentCoroutine;
public void SetCoroutineParameters(int someInt, float someFloat)
{
m_CurrentCoroutineFactory = CreateCoroutineFactory(someInt, someFloat);
}
public void RestartCurrentCoroutine()
{
if (m_CurrentCoroutine != null)
{
StopCoroutine(m_CurrentCoroutine);
m_CurrentCoroutine = null;
}
if (m_CurrentCoroutineFactory != null)
{
m_CurrentCoroutine = m_CurrentCoroutineFactory();
StartCoroutine(m_CurrentCoroutine);
}
}
}