methodName | 协程的名称。 |
routine | 代码中函数的名称,包括协程。 |
停止此行为上运行的第一个名为 methodName
的协程,或存储在 routine
中的协程。
StopCoroutine 接受三个参数之一,这些参数指定停止哪个协程
IEnumerator
变量。Coroutine
的 Coroutine
。
注意:不要混合这三个参数。如果在 StartCoroutine 中使用字符串作为参数,请在 StopCoroutine 中使用该字符串。类似地,在 StartCoroutine 和 StopCoroutine 中都使用 IEnumerator
。最后,使用 Coroutine
用于创建的 StopCoroutine
。
在 CS 示例中,使用了 IEnumerator 类型。
using UnityEngine; using System.Collections;
public class Example : MonoBehaviour { // keep a copy of the executing script private IEnumerator coroutine;
// Use this for initialization void Start() { print("Starting " + Time.time); coroutine = WaitAndPrint(3.0f); StartCoroutine(coroutine); print("Done " + Time.time); }
// print to the console every 3 seconds. // yield is causing WaitAndPrint to pause every 3 seconds public IEnumerator WaitAndPrint(float waitTime) { while (true) { yield return new WaitForSeconds(waitTime); print("WaitAndPrint " + Time.time); } }
void Update() { if (Input.GetKeyDown("space")) { StopCoroutine(coroutine); print("Stopped " + Time.time); } } }
以下 cs 示例展示了如何使用 StopCoroutine(Coroutine)。
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ExampleClass : MonoBehaviour { void Start() { StartCoroutine(coroutineA()); }
IEnumerator coroutineA() { // wait for 1 second yield return new WaitForSeconds(1.0f); Debug.Log("coroutineA() started: " + Time.time);
// wait for another 1 second and then create b yield return new WaitForSeconds(1.0f); Coroutine b = StartCoroutine(coroutineB());
yield return new WaitForSeconds(2.0f); Debug.Log("coroutineA() finished " + Time.time);
// B() was expected to run for 10 seconds // but was shut down here after 3.0f StopCoroutine(b); yield return null; }
IEnumerator coroutineB() { float f = 0.0f; float start = Time.time;
Debug.Log("coroutineB() started " + start);
while (f < 10.0f) { Debug.Log("coroutineB(): " + f); yield return new WaitForSeconds(1.0f); f = f + 1.0f; }
// Intended to handling exit of the this coroutine. // However coroutineA() shuts coroutineB() down. This // means the following lines are not called. float t = Time.time - start; Debug.Log("coroutineB() finished " + t); yield return null; } }