Unity---协程的简单使用

1、作用

协程的作用一共有两点:

  1. 延时执行代码。
  2. 在某项操作完后再执行代码。

就是控制代码在特性的时间执行。

2、协程和线程的区别

  1. 协程不是异步,不需要考虑同步和锁问题
  2. 线程避免了无意义的调度,提高了性能,但需要程序员自己承担调度责任。
  3. 协程无法多核同时进行。

3、C#中的IEnumerator(迭代器)

协程其实就是一个IEnumerator(迭代器),IEnumerator有两个方法和一个属性。
MoveNext():迭代到下一个元素
Reset():重置迭代
Current:返回当前集合中正迭代的一个元素

可枚举的接口 IEnumerable,
GetEnumerator():返回枚举器接口方法。

使用迭代器实现foreach功能

static void Main(string[] args)
{
    int[] arr = new int[5] { 12, 65, 749, 16, 49 };

    //foreach (int item in arr)
    //{
    //    Console.WriteLine(item);
    //}

    IEnumerator e = arr.GetEnumerator(); //获取要迭代的对象
    while (e.MoveNext())  //一个一个的读取元素,读取完会返回false
    {
        Console.WriteLine(e.Current);  //输出读取内容
    }

    Console.ReadKey();
}

 

IEnumerator方法的用法

void Start () {
    IEnumerator e = TestCoroutine();
    while (e.MoveNext())  //一直读取到有yield的语句才会停止执行下面的代码
    {
        Debug.Log(count++);
        Debug.Log(e.Current);  //输出yield return里面的内容
    }
}
IEnumerator TestCoroutine()
{
    Debug.Log("num1");
    Debug.Log("num1");
    Debug.Log("num1");
    yield return null;
    Debug.Log("num2");
    yield return 2;
    Debug.Log("num3");
    yield return new WaitForSeconds(1);
    Debug.Log("num4");
    yield break;
}
/*输出结果
num1
num1
num1
1
Null
num2
2
2
num3
3
UnityEngine.WaitForSeconds
num4
*/

 

4、Unity中的协程使用

推荐一篇博客CSDNhuang9012
写的超级好,由于比较长就不搬运了,可以直接去看

 

5、其他使用

WaitUntil

在协程中的WaitUntil会将协程挂起,当其内函数TestWaitUntil返回true时才会继续执行协程下面的代码。

    IEnumerator Test()
    {
        yield return new WaitUntil(TestWaitUntil);
        Debug.Log("111");
    }

    private bool TestWaitUntil()
    {
        return true;
    }

WaitWhile

和WaitUntil类似,但是不会将协程挂起。

转载于:https://www.cnblogs.com/Fflyqaq/p/10598006.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值