Unity StartCoroutine 和 C# yield

using UnityEngine;

public class CoroutineTest : MonoBehaviour
{
    void Start()
    {
        Debug.Log(Time.frameCount + " : start ");
        StartCoroutine(CoroutineA());
        Debug.Log(Time.frameCount + " : end ");
    }


    IEnumerator CoroutineA()
    {
        Debug.Log(Time.frameCount + " : A 1");
        yield return null;
        Debug.Log(Time.frameCount + " : A 2");
        yield return StartCoroutine(CoroutineB());
        Debug.Log(Time.frameCount + " : A 3");
    }

    IEnumerator CoroutineB()
    {
        Debug.Log(Time.frameCount + " : B 1");
        yield return null;
        Debug.Log(Time.frameCount + " : B 2");
        yield return StartCoroutine(CoroutineC());
        Debug.Log(Time.frameCount + " : B 3");
        yield return null;
        Debug.Log(Time.frameCount + " : B 4");
    }

    IEnumerator CoroutineC()
    {
        Debug.Log(Time.frameCount + " : C 1");
        yield return null;
        Debug.Log(Time.frameCount + " : C 2");
        yield return null;
        Debug.Log(Time.frameCount + " : C 3");
        yield return null;
        Debug.Log(Time.frameCount + " : C 4");
    }
}

输出:

Unity StartCoroutine 和 C# yield_第1张图片


如下注释的部分引用了"yield return”,其功能相当于之后的所有代码。

可以看到如果不适用yield需要些很多代码来支持遍历操作。

yield return 表示在迭代中下一个迭代时返回的数据,除此之外还有yield break, 其表示跳出迭代。

public class YieldTest
{
    static void Main(string[] args)
    {
        HelloCollection helloCollection = new HelloCollection();
        foreach (string s in helloCollection)
        {
            Console.WriteLine(s);
        }

        Console.ReadLine();
    }
}

//public class HelloCollection : IEnumerable
//{
//    public IEnumerator GetEnumerator()
//    {
//        yield return "Hello";
//        yield return "World";
//    }
//}

public class HelloCollection : IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        Enumerator enumerator = new Enumerator(0);
        return enumerator;
    }

    public class Enumerator : IEnumerator, IDisposable
    {
        private int state;
        private object current;

        public Enumerator(int state)
        {
            this.state = state;
        }

        public bool MoveNext()
        {
            switch (state)
            {
                case 0:
                    current = "Hello";
                    state = 1;
                    return true;
                case 1:
                    current = "World";
                    state = 2;
                    return true;
                case 2:
                    break;
            }
            return false;
        }

        public void Reset()
        {
            throw new NotSupportedException();
        }

        public object Current
        {
            get { return current; }
        }

        public void Dispose()
        {
        }
    }
}





你可能感兴趣的:(Unity3D开发,C#开发)