- Home /
Can you end a coroutine from outside of that coroutine?
I'm not exactly sure how else to word this question, so the way I titled it may be inaccurate.
But basically, I am running an AI that is a basic finite state machine with an ienumerable with a few different states, and I do a bunch of checks to see which state the AI should be in, set the state, then do a switch on the state and perform whatever action is associated with that state (a coroutine, like (yield Wander(), yield Chase(), yield Attack(), etc). But inside each of those coroutines, I have to basically do the same check I did that got me in this state in the first place, to determine when I should return and get out of it.
I wish I could just somehow have the check I originally did running simultaneously the whole time, and could switch the states even when the AI is in one of the coroutines associated with a different state. Is something like that possible?
Answer by Loius · Dec 31, 2010 at 08:17 PM
Have your coroutines do something like -
function AttackCoroutine() { while ( state == Attack ) { // do stuff yield; } }
function PatrolCoroutine() { while ( state == Patrol ) { // do stuff yield; } }
Then your main AI-choice-decision-thing can just set state to the desired state and start a coroutine; the others will gracefully break out then.
if ( state != Attack && playerIsCloseEnough ) {
state = Attack;
StartCoroutine( AttackCoroutine ); // or however it is you invoke coroutines
}
Oh my gosh... When you explain it like that, the solution is so delightfully simple it's embarrassing. Thanks man!
Answer by yoyo · Jan 01, 2011 at 02:03 AM
If you have to stop a coroutine, then if you start it by name (string, not method call) you can also stop it by name.
http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.StopCoroutine.html
Unfortunately this will stop all running coroutines with that name (for the current instance of the MonoBehaviour, not all GameObjects running the behaviour).
This post is quite old and now, You can also store the Coroutine object given by StartCoroutine and call stop on him if you don't want to use it by name
Your answer
Follow this Question
Related Questions
Tracking state changes using yield 0 Answers
How to start at a specific coroutine? 0 Answers
How often should I Yield the next frame in a coroutine for performance optimization? 2 Answers
FSM and coroutine problem 2 Answers
Can I use WWW in Start()? 1 Answer