你是不是遇到过协程停不了的情况?你是直接调用IEnumerator方法,如下?
void Start () { StartCoroutine(IETest01()); StartCoroutine(IETest02()); } IEnumerator IETest01() { Debug.LogError("IETest01"); yield return new WaitForSeconds(1); StopCoroutine(IETest02()); yield return new WaitForSeconds(1); Debug.LogError("IETest01 end"); } IEnumerator IETest02() { Debug.LogError("IETest02"); yield return new WaitForSeconds(2); Debug.LogError("IETest02 end"); }
不是协程停不了,是处理的方式不对。上面代码StopCoroutine(IETest02());相当于再调用了一次IETest02方法,和第一次调用StartCoroutine(IETest02());时返回的并不是同一个值。这里很好理解,普通的方法,多次调用,返回的值也不会指向同一段地址。
那么正确的方法应该怎么做呢?下面有三种参考方法:
1、通过函数名字符串
void Start () { StartCoroutine("IETest01"); StartCoroutine("IETest02"); } IEnumerator IETest01() { Debug.LogError("IETest01"); yield return new WaitForSeconds(1); StopCoroutine("IETest02"); yield return new WaitForSeconds(1); Debug.LogError("IETest01 end"); } IEnumerator IETest02() { Debug.LogError("IETest02"); yield return new WaitForSeconds(2); Debug.LogError("IETest02 end"); }
2、把返回值(IEnumerator )保存下来
IEnumerator ie1; IEnumerator ie2; void Start () { ie1 = IETest01(); ie2 = IETest02(); StartCoroutine(ie1); StartCoroutine(ie2); } IEnumerator IETest01() { Debug.LogError("IETest01"); yield return new WaitForSeconds(1); StopCoroutine(ie2); yield return new WaitForSeconds(1); Debug.LogError("IETest01 end"); } IEnumerator IETest02() { Debug.LogError("IETest02"); yield return new WaitForSeconds(2); Debug.LogError("IETest02 end"); }
后面两段代码执行不会打印"IETest02 end",协程中断成功
3、把StartCoroutine方法的返回值(Coroutine)保存起来
Coroutine c1, c2; void Start() { c1 = StartCoroutine(IETest01(100)); c2 = StartCoroutine(IETest02()); } IEnumerator IETest01(int v) { Debug.LogError("IETest01:" + v); yield return new WaitForSeconds(1); StopCoroutine(c1); yield return new WaitForSeconds(1); Debug.LogError("IETest01 end"); } IEnumerator IETest02() { Debug.LogError("IETest02"); yield return new WaitForSeconds(2); Debug.LogError("IETest02 end"); }