线程(Thread)和协程(Coroutine)
协程不是线程,也不是异步执行的。协程和 MonoBehaviour 的 Update函数一样也是在MainThread中执行的。使用协程你不用考虑同步和锁的问题。
协程的简单使用
void Start()
{
StartCoroutine("tmp");
}
IEnumerator tmp()
{
while (true)
{
yield return new WaitForSeconds(1);
Debug.Log("sghjd");
}
}
运行结果没间隔1秒打印“sghjd”。若是没有while(true)则等待一秒然后只打印一次。
Yield
IEnumerator 的返回值,当你“yield”一个方法时,你相当于说了,“现在停止这个方法,然后在下一帧中从这里重新开始!”。
注意:用0或者null来yield的意思是告诉协程等待下一帧,直到继续执行为止。
void Start()
{
StartCoroutine("tmp");
Debug.Log("start");
}
private void Update()
{
if(Time.frameCount==1)
{
Debug.Log("timeF 1");
}
if (Time.frameCount == 2)
{
Debug.Log("timeF 2");
}
if (Time.frameCount == 3)
{
Debug.Log("timeF 3");
}
if (Time.frameCount == 4)
{
Debug.Log("timeF 4");
}
}
IEnumerator tmp()
{
Debug.Log("1");
yield return null;
Debug.Log("2");
yield return null;
Debug.Log("3");
}
这里解释一下为什么"timeF 1"打印接着就到“timeF 2”:unity 脚本的运行次序是start(), 才到update()因此先打印start()里得内容,再打印“timeF 1”
第一帧执行完后因为update(),先于Coroutine,所以先打印“timeF 2”
开启协程
StartCoroutine("tmp");
StartCoroutine(tmp());
关闭协程
StopAllCoroutines();//关闭所有协程注意,这只会终止在调用该方法的对象中
StopCoroutine("tmp");//注意开启协程传递字符,关闭也要传递字符
注意
this.enabled = false; 会停止update();运行但是协程还在运行
this.gameObject.SetActive(false);update 和协程都会停止运行