Its definitely frustrating theres no StopCoroutine that takes a Coroutine. I rarely ever start them with a string to begin with.
So one way you could accomplish this is by using something like this:
-
class CancellingCoroutine : IEnumerator
-
{
-
public bool stop;
-
-
IEnumerator enumerator;
-
MonoBehaviour behaviour;
-
-
public readonly Coroutine coroutine;
-
-
{
-
this. behaviour = behaviour;
-
this. enumerator = enumerator;
-
}
-
-
public object Current { get { return enumerator. Current; } }
-
public bool MoveNext { return !stop && enumerator. MoveNext ( ); }
-
public implicit operator YieldStatement ( CancellingCoroutine self ) { return self == null ? null : self. coroutine; }
-
}
Then to start it you would do:
-
CancellingCoroutine ccoroutine = new CancellingCoroutine ( this, CoFunctionEnumerator ( ) );
To wait for it
-
yield return ccoroutine. coroutine;
Then to stop it
-
ccoroutine. stop = true;
Its a hacky work around and it would be alot better if YieldStatement wasnt functionally sealed.
If you change your IEnumerator functions to use IEnumerator<YieldStatement> instead it'd be best. But i don't know how that would fair for builtin stuff like Start...
You could also set a done variable in the class when MoveNext returns false, thus allowing you to wait multiple times.
转载unity3d论坛:http://forum.unity3d.com/threads/102817-Coroutine-Control-and-StartCoroutine()-Coroutine