Unity3d之协程自实现测试

using UnityEngine;
using System.Collections;

public class TestStartCoroutine : MonoBehaviour
{
    IEnumerator m_etor;
    bool m_moveNext;
    MyWaitForSeconds m_waiter;

    #region MyRegion

    class MyWaitForSeconds
    {
        int m_seconds;
        float m_timer;

        public MyWaitForSeconds(int seconds)
        {
            m_seconds = seconds;
            m_timer = 0;
        }

        public bool Update(float deltaTime)
        {
            m_timer += deltaTime;
            return m_timer >= m_seconds;
        }
    }

    #endregion

    void Start()
    {
        MyStartCoroutine(T1());
    }

    public void MyStartCoroutine(IEnumerator etor)
    {
        m_etor = etor;
        m_moveNext = true;
    }

    IEnumerator T1()
    {
        Debug.Log("#1");

        int i = 0;
        while (i++ < 60)
        {
            Debug.Log("#2  " + i);
            yield return null;
        }

        Debug.Log("#3");

        yield return new MyWaitForSeconds(3);

        Debug.Log("#4");
    }

    void Update()
    {
        if (m_moveNext)
        {
            if (!m_etor.MoveNext())
                m_moveNext = false;
            else if (m_etor.Current is MyWaitForSeconds)
            {
                m_waiter = (MyWaitForSeconds)m_etor.Current;
                m_moveNext = false;
            }
        }

        if (m_waiter != null)
        {
            if (m_waiter.Update(Time.deltaTime))
            {
                m_waiter = null;
                m_moveNext = true;
            }
        }
    }
}

  Unity3d的协程是利用枚举器来实现的,我猜可能是跟以上测试代码一样,在一帧里让枚举器的指针加1,从而可以等待1帧。

posted @ 2015-08-21 18:02  孤独の巡礼  阅读(282)  评论(0编辑  收藏  举报