協程方法的開啟、關閉都是由對象完成的,所以我們在開啟、關閉時都需要弄清楚對象,否則很容易出現協程打不開,或者關不掉的情況。
協程方法的開啟、關閉方法1:用字符串打開,用字符串關閉,如果需要傳遞參數,可以在字符串后面寫參數,但是參數個數只能為1。
1 public class Test 2 { 3 private void Start() 4 { 5 this.StartCoroutine("IEDo");//開啟 6 this.StartCoroutine("IEDo1", 1);//開啟並傳參 7 this.StopCoroutine("IEDo");//關閉 8 this.StopCoroutine("IEDo1");//關閉 9 } 10 11 IEnumerator IEDo() 12 { 13 yield return null; 14 } 15 16 IEnumerator IEDo1(int a) 17 { 18 yield return null; 19 } 20 }
協程方法的開啟、關閉方法2:用方法名打開協程,但關閉時會稍微麻煩點,如下圖所示,通過打開時的返回值去關閉。
1 public class Test : Base 2 { 3 private void Start() 4 { 5 Coroutine cc = this.StartCoroutine(IEDo());//開啟 6 this.StopCoroutine(cc);//關閉 7 } 8 9 IEnumerator IEDo() 10 { 11 yield return null; 12 } 13 }
協程方法的開啟、關閉方法3:在協程方法中設置一個特定的條件,當這個條件滿足時,用 break 或者 yield break 讓協程自己關閉。
1 public class Test : Base 2 { 3 private bool val; 4 5 private void Start() 6 { 7 this.StartCoroutine("IEDo");//開啟 8 } 9 10 IEnumerator IEDo() 11 { 12 while (true) 13 { 14 yield return null; 15 if (val) 16 { 17 //當布爾值 val 為真時,使用 break 或者 yield break 讓協程自己關閉。 18 //break; 19 yield break; 20 } 21 } 22 }
另外需要注意: StopAllCoroutines() 這個方法也僅僅只能關閉調用這個方法的對象身上的所有協程,而不能關閉其他對象身上的協程。
