Unity3D 协程 浅谈

理解:协程不是线程,也不是异步执行(知道就行)。

1.协程和MonoBehaviour的Update函数一样,也是在MainThread中执行的(一定得明白这句话意思)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void  Start () {
     StartCoroutine(HelloCoroutine());
}
 
void  Update () {
     Debug.Log( "Update..." );
}
void  LateUpdate()
{
     Debug.Log( "LateUpdate..." );
}
IEnumerator HelloCoroutine()
{
     while  ( true )
     {
         Debug.Log( "Coroutine..." );
         yield  return  null ;
     }
}


1
 
 
对比以上代码和两张截图。这样写协程,好像是高级一点的Update写法。至少应该可以看出,这种写法的协程可以完成update的功能。

2.与update不一样的地方。
1
2
3
4
5
6
7
8
9
10
11
12
IEnumerator Count()
    {
        int  seconds = 0;
        while  ( true )
        {
            for  ( float  timer = 0; timer < 2; timer += Time.deltaTime)
                yield  return  0;
 
            seconds++;
            Debug.Log(seconds +  " seconds have passed since the Coroutine started." );
        }
    }<br>

  

3.yield

  yiled return null  等同于 yield return 0

我这边的理解是,停止正在执行的方法,并从下一帧开始执行(一般是0.02秒,与Update的每一帧是一样的,具体看Unity设置的timer)。

 

4.协程是可以传递参数的。

5.协程还可以嵌套协程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
IEnumerator HelloCoroutinue()
     {
         Debug.Log( "Start----" );
         yield  return  StartCoroutine(Wait(0.2f));  //  yield return new WaitForSeconds(0.2f);最终达到的效果是一样的。
         Debug.Log( "End----" );
}
     IEnumerator Wait( float  s)
     {
         for ( float  timer =0;timer< s;timer+=Time.deltaTime)
         {
             Debug.Log( "当前 timer"  + timer.ToString());
             yield  return  0;  // yield return null;
         }
         Debug.Log( "Wait....." );
     }

  

看截图中画线的时间差,再次验证了与Update好像。暂停的时间都是一样的。

可以看到暂停了当前的方法去执行yield return后的方法。

 

补充注意: 

           a.多个协程可以同时运行,它们会根据各自的启动顺序来更新;

    b.如果你想让多个脚本访问一个协程,可以定义为静态的协程;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值