最近在看unity coroutine相关内容,基于自己的理解写了mycoroutine;
后边的接口和实现类,偷懒就直接写在MyCoroutine了。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyCoroutine : MonoBehaviour {
int frame = 0;
IEnumerator ie;
void Start()
{
ie = myCoroutine();
}
void LateUpdate()
{
if(ie != null)
{
if(ie.Current != null)
{
IWait wait = (IWait)ie.Current;
if(wait.Tick())
{
ie.MoveNext();
}
}
else
{
ie.MoveNext();
}
}
frame ++;
}
IEnumerator myCoroutine()
{
yield return new WaitForSomeFrame(1);
Debug.Log("myCoroutine Frame:" + frame);
yield return new WaitForSomeFrame(10);
Debug.Log("myCoroutine Frame:" + frame);
yield return new WaitForSomeTime(1);
Debug.Log("myCoroutine Frame:" + frame);
}
interface IWait
{
bool Tick();
}
class WaitForSomeFrame:IWait
{
private int frame = 0;
public WaitForSomeFrame(int frame)
{
this.frame = frame;
}
public bool Tick()
{
frame --;
return frame <= 0;
}
}
class WaitForSomeTime:IWait
{
private float time = 0;
public WaitForSomeTime(float time)
{
this.time = time;
}
public bool Tick()
{
time -= Time.deltaTime;
return time <= 0;
}
}
}