Using coroutines on states

I am doing the Unity 3rd Person Combat & Traversal course and want to use coroutines in my custom states, but I can’t use StartCoroutine() since it’s not being recognized. How can I solve this?

Error|CS0103|The name 'StartCoroutine' does not exist in the current context

Thank you!

StartCoroutine - and all other coroutine-related methods - exist on the MonoBehaviour. But fortunately the methods are public. The simplest way to execute a coroutine in your state is to use the state machine (which is a MonoBehaviour and you should have a reference to it in your state)

In your state

statemachine.StartCoroutine(MyCoroutine());

This does clump all your coroutines into the same object which means you can start a coroutine in one state and stop it in another because the coroutine is being executed by the state machine and not the state. Across entities, I mean. You can’t stop the enemy’s coroutine from the player’s state machine. Unless you started it on the payer’s state machine, which would be a nightmare to debug.

1 Like

Thank you very much!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms