赞
踩
- 一、yeild return null
- void Start(){
- Debug.Log("start1");
- StartCoroutine(Test());
- Debug.Log("start2");
- }
-
- IEnumerator Test(){
- Debug.Log("test1");
- yeild return null;
- Debug.Log("test1");
- }
-
- 运行结果是:strat1 test1 start2 test2
-
- 当被调用函数执行到yield return null(暂停协程,等待下一帧继续执行)时,根据Unity解释协同程序就会被暂停,其实我个人认为他这个解释不够精确,先返回开始协程的地方,然后再暂停协程。也就是先通知调用处,“你先走吧,不用管我”,然后再暂停协程。
-
-
-
- 二、yeild return new WaitForSecondes(1.0f)
- void Start(){
- Debug.Log("start1");
- StartCoroutine(Test());
- Debug.Log("start2");
- }
-
- IEnumerator Test(){
- Debug.Log("test1");
- yeild return new WaitForSecondes(1.0f);
- Debug.Log("test1");
- }
-
- 运行结果是:strat1 test1 start2 test2(test2等待三秒后打印出来)
- IEnumerator Init()
- {
- yield return StartCoroutine(init1());
- Debug.Log("init1 finish");
- yield return StartCoroutine(init2());
- Debug.Log("init2 finish");
- yield return StartCoroutine(init3());
- Debug.Log("init3 finish");
- }
-
- IEnumerator init1()
- {
- // 模拟初始化
- yield return new WaitForSeconds(2);
- }
- IEnumerator init2()
- {
- // do somthing..
- yield return new WaitForSeconds(2);
- }
- IEnumerator init2()
- {
- // do somthing..
- yield return new WaitForSeconds(2);
- }
-
- 这样调用能保证,init1,init2,init3一个一个的执行,不至于出现后面执行的代码引用一个前面未初始化的变量
-
-
-
-
-
- void Start () {
- Debug.Log("start1");
- StartCoroutine(Test());
- Debug.Log("start2");
- }
-
- IEnumerator Test()
- {
- Debug.Log("test1");
- yield return StartCoroutine(DoSomething());
- Debug.Log("test2");
- }
-
- IEnumerator DoSomething()
- {
- Debug.Log("load 1");
- yield return null;
- Debug.Log("load 2");
- }
-
- 执行结果:start1 test1 load1 start2 load2 test2
- 这种StartCoroutine中嵌套一个yield return StartCoroutine,第一个StartCoroutine会等到第二个StartCoroutine中所有代码结束后再继续执行,而第二个StartCoroutine中的yield语句会先返回第一个,然后立即返回他的调用处,也就是调用处会继续执行,而第一个StartCoroutine会等待第二个执行完再继续执行。
7、yield return 注意的地方
- IEnumerator Queue()
- {
- for (int i = 0; i < activity.Count; i++)
- {
- PlayerControl pc = activity[i];
- yield return CoroutineManger.GetInstance().StartCoroutine(pc.Target1());
-
- //当AtkTarget1的协程耗时较大时,没有执行完AtkTarget1中的协程就可能就执行AtkTarget2
- yield return CoroutineManger.GetInstance().StartCoroutine(pc.Target2());
-
- //直到AtkTarget2中的协程才执行执行AtkTarget3
- yield return CoroutineManger.GetInstance().StartCoroutine(pc.Target3());
- }
- }
-
-
- public IEnumerator Target1()
- {
- CoroutineManger.GetInstance().StartCoroutine(A1());
- CoroutineManger.GetInstance().StartCoroutine(A2());
- }
-
- public IEnumerator Target2()
- {
- yield return CoroutineManger.GetInstance().StartCoroutine(A1());
- yield return CoroutineManger.GetInstance().StartCoroutine(A2());
- _temp.Clear();
- }
-
- public IEnumerator Target3()
- {
- yield break;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。