我有一种方法可以启动协程,并且应该先停止协程并重设一些内容,然后再重新启动。
private Coroutine wholeTutorialRoutine;
public void RunWholeTutorial()
{
tutorialText.text = "";
StopAllCoroutines();
if(wholeTutorialRoutine != null)
{
StopCoroutine(wholeTutorialRoutine);
}
wholeTutorialRoutine = StartCoroutine(WholeTutorial());
}
private IEnumerator WholeTutorial()
{
// Wait until after we are done showing this dialouge
yield return StartCoroutine(ShowDialougForSeconds("tap_to_kill", 5f));
yield return new WaitForSeconds(5f);
yield return StartCoroutine(ShowDialougForSeconds("larger_enemies", 5f));
yield return new WaitForSeconds(5f);
yield return StartCoroutine(ShowDialougForSeconds("press_button", 7f));
yield return new WaitForSeconds(3f);
yield return StartCoroutine(ShowDialougForSeconds("button_colors", 5f));
}
private IEnumerator ShowDialougForSeconds(string diagID, float time)
{
SetText(diagID);
tutorialText.GetComponent<Animator>().SetTrigger("FadeIn");
yield return new WaitForSeconds(time);
tutorialText.GetComponent<Animator>().SetTrigger("FadeOut");
}
wholeTutorialRoutine
是类型为Coroutine
的专用字段。我觉得这些
WaitForSeconds
调用发生了一些时髦的事情,但是我不太确定该怎么办。RunWholeTutorial()
连接到一个按钮,所以我想停止当前教程,如果用户一遍又一遍地按它,请重新开始。当前发生的事情似乎是协程在彼此之上运行。
最佳答案
使用IEnumerator
代替Coroutine
在RunWholeTutorial
函数中一次存储Start
协程函数的实例。然后,您可以使用该IEnumerator
变量启动和停止它。
private IEnumerator wholeTutorialRoutine;
void Start()
{
wholeTutorialRoutine = WholeTutorial();
}
public void RunWholeTutorial()
{
tutorialText.text = "";
if (wholeTutorialRoutine != null)
{
StopCoroutine(wholeTutorialRoutine);
}
StartCoroutine(wholeTutorialRoutine);
}
private IEnumerator WholeTutorial()
{
// Wait until after we are done showing this dialouge
yield return StartCoroutine(ShowDialougForSeconds("tap_to_kill", 5f));
yield return new WaitForSeconds(5f);
yield return StartCoroutine(ShowDialougForSeconds("larger_enemies", 5f));
yield return new WaitForSeconds(5f);
yield return StartCoroutine(ShowDialougForSeconds("press_button", 7f));
yield return new WaitForSeconds(3f);
yield return StartCoroutine(ShowDialougForSeconds("button_colors", 5f));
}
private IEnumerator ShowDialougForSeconds(string diagID, float time)
{
SetText(diagID);
tutorialText.GetComponent<Animator>().SetTrigger("FadeIn");
yield return new WaitForSeconds(time);
tutorialText.GetComponent<Animator>().SetTrigger("FadeOut");
}