void Awake()
{
StartCoroutine(SayHello());
}
private IEnumerator SayHello()
{
for (int i = 0; i < 10; i++)
{
Debug.Log("逻辑处理片段....begin");
Debug.Log("current unit :..............." + i);
yield return 2.0f;
Debug.Log("逻辑处理片段....end");
}
}
C#迭代器
StartCorotine其实是启动一个事件,这个事件可以是Mono默认的事件,也可以是我们自己定义的; using UnityEngine;
using System.Collections;
public class WaitUntilExample : MonoBehaviour
{
public int frame;
void Start()
{
StartCoroutine(Example());
}
IEnumerator Example()
{
Debug.Log("Waiting for princess to be rescued...");
yield return new WaitUntil(() => frame >= 10);
Debug.Log("Princess was rescued!");
}
void Update()
{
if (frame <= 10)
{
Debug.Log("Frame: " + frame);
frame++;
}
}
}
yield WaitWhile:等待委托Func using UnityEngine;
using System.Collections;
public class WaitWhileExample : MonoBehaviour
{
public int frame;
void Start()
{
StartCoroutine(Example());
}
IEnumerator Example()
{
Debug.Log("Waiting for prince/princess to rescue me...");
yield return new WaitWhile(() => frame < 10);
Debug.Log("Finally I have been rescued!");
}
void Update()
{
if (frame <= 10)
{
Debug.Log("Frame: " + frame);
frame++;
}
}
}
yield return 的返回值,我们可以根据自己需求来定义协程何时被继续执行;必须继承抽象类CustomYieldInstruction,实现KeepWaiting的Get方法.
using System.Collections;
using UnityEngine;
public class ExampleScript : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonUp(0))
{
Debug.Log("Left mouse button up");
StartCoroutine(waitForMouseDown());
}
}
public IEnumerator waitForMouseDown()
{
yield return new WaitForMouseDown();
Debug.Log("Right mouse button pressed");
}
}
自定义:YieldInstruction
using UnityEngine;
public class WaitForMouseDown : CustomYieldInstruction
{
public override bool keepWaiting
{
get
{
return !Input.GetMouseButtonDown(1);
}
}
public WaitForMouseDown()
{
Debug.Log("Waiting for Mouse right button down");
}
}