unity3D之协程Coroutine

第二次写博客,对于unity3D的学习已经持续了近两个月,最近被其中的协程困惑好久,研究下简单写个记录供你们参考,欢迎各位大神指正错误。html


一个最简单的实现协程的代码:异步

using UnityEngine;
using System.Collections;

public class coroutine : MonoBehaviour {

	// Use this for initialization
	void Start () {
        StartCoroutine(beginCoroutine());
	}

    public IEnumerator beginCoroutine()
    {
        yield return new WaitForSeconds(1.0f);
    }

	// Update is called once per frame
	void Update () {
	
	}
}
StartCoroutine():开启一个协程,能够是函数或者函数名称字符串,这里主要和结束协程StopCoroutine()有关。具体用法参照:点击打开连接
返回参数必须是IEnumerator,用yield return获得返回值。这里留个坑,IEnumerator和IEnumerable两个接口和yield用法暂时没搞清楚,过两天补上。
那么,这里主要介绍协程的使用注意,对于协程来讲,小弟通过屡次测试的验证发现结论就是必定要慎重使用协程!

第一,协程不一样于线程,协程不是异步执行的,也就是说协程是做为一种函数在主函数中被调用的。函数

第二,C#中WaitForSeconds()函数不能直接使用,只能经过调用协程使用。也就是要实现过几秒执行的效果会用到协程。(Invoke()也留个坑)。学习

第三,yield的用法就至关于说:返回调用的函数,而后下一帧从这里从新开始。测试

具体给出一段测试函数。this

using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {

    public static int count=0;
	// Use this for initialization
	void Start () {
        int i = 0;
        Debug.Log("start主函数");
        StartCoroutine(begin(i)); //第十行
        i++;
        Debug.Log("end 主函数" + i+","+count);
        Debug.Log("2222end 主函数" + i + "," + count);

	}

    public IEnumerator begin(int i)
    {

        Debug.Log("start 协成");
        count++;
        i++;
        Debug.Log("end 协成" + i + ", " + count);
        yield return new WaitForSeconds(3f);
        Debug.Log("return 协成完毕" + i + ", " + count);
        Debug.Log("2222end 协成" + i + ", " + count);

        

    } 
	// Update is called once per frame
	void Update () {
        
	}
}
在第十行调入协程后,会一直执行协程函数内的语句,直到碰见return。注意:此时执行WaitForSecond()函数,而后在当前帧继续执行调用协程的函数,也就是Start()内的代码,直到结束。下一帧回到协程函数内部,执行yeild return后面代码,直到函数结束。总之对于协程的使用必定要当心,若是只想实现延迟几秒,那么最好在Start()内调用协程以后不要有继续执行代码,或者控制好协程的stop。

代码执行结果:spa


相关知识连接:点击打开连接.net