Copy //type 1
IEnumerator CoroFunc1()
{
yield return null;
}
//type 2 yield return type is limited to string
IEnumerator<string> CoroFunc2()
{
yield return "hello";
}
//type 3 with param
IEnumerator<string> CoroFunc3(string str)
{
yield return "hello" + str;
}
//type 4 return IEnumerable: not necessary.
IEnumberable CoroFunc4(int i)
{
yield return null;
}
Copy //type 1 use anywhere inside a monobehaviour class
Coroutine coro = StartCoroutine(CoroFunc1());
//type 2 use inside a coroutine, unity automatically create a Coroutine, and call it next frame.
yield return CoroFunc1();
//type 3 just don't use it, very slow
Coroutine coro = StartCoroutine("CoroFunc4", 1);
Copy bool finishCondition = false;
yield return new WaitUntil(() => finishCondition)
//go on when finishCondition is true
Copy //pseudocode
var retCode = yield return new XXX();
Print(retCode);
Copy public class CoroutineWithData : CustomYieldInstruction
{
public int retCode { get; private set; }
private bool _finished = false;
public void onFinished(bool isSucc)
{
_finished = true;
retCode = isSucc ? 0 : -1;
}
//must override this
public override bool keepWaiting
{
get
{
return !_finished;
}
}
}
//how to use:
public class main : MonoBehaviour {
private IEnumerator Start()
{
CoroutineWithData coro = new CoroutineWithData();
yield return coro;
Debug.Log("retcode:" + coro.retCode);
}
//click btn to continue coro
public void btnClickHandler()
{
coro.onFinished(true);
}
}
Copy IEnumerator A()
{
yield return StartCoroutine(B());
//wait for B() finishes
}
IEnumerator AA() { Coroutine sub1 = StartCoroutine(B()); Coroutine sub2 = StartCoroutine(B());
Copy //do sth at the same time
yield return sub1;
yield return sub2;
//wait for all finishes
Copy ## 多态协程
```cs
//parent class:
protected virtual IEnumberator DoSomething()
{
yield return null;
}
//child class
protected override IEnumberator DoSomething()
{
//you can call base like this:
yield return StartCoroutine(base.DoSomething();
//do something
}