So i have a coroutine that waits and changes a variable every two seconds:
IEnumerator moveAnimal(float animalSpeed){
speedZ = animalSpeed;
yield return new WaitForSeconds(2);
speedZ = 0;
yield return new WaitForSeconds(2);
}
I have no idea what to do now… I made sure all of the surrounding code works perfectly, so the problem is in the coroutine. Is there a stupid mistake I’m making here?
“Every 2 seconds” sounds suspicious given your code. Where and when do you start your coroutine? The last WaitForSeconds is pretty pointless in your case unless you wait for the coroutine completion in another coroutine.
Keep in mind that StartCoroutine will start a new coroutine when called. You can start the same coroutine several times. When starting it in Update you get a new coroutine every frame. So there would be hundreds of coroutines running at the same time. Im most cases where you want something to happen at a regular interval you want to start the coroutine once in Start and use a loop inside the coroutine
Note that started coroutines run “on their own” once started. They are handled by the coroutine scheduler of Unity. The coroutine runs on the MonoBehaviour instance you used to call StartCoroutine (StartCoroutine is an instance method of MonoBehaviour). If the MonoBehaviour is disabled or destroyed the coroutine will be terminated.
If this doesn’t solve your issue you have to be more specific about where and when you start the coroutine and what exact behaviour you expected.