Weird Coroutine Behaviour

I’m not sure how to describe this problem, as I’m unable to consistently reproduce it. I’ll try my best:

  • My game has different UI screens (a shop, the title screen, game over screen, etc)
  • The screens animate into and out of view through the use of coroutines
  • the coroutines that animate them out disable them so that they don’t take up memory
  • sometimes, they don’t animate out fully

I know this is very abstract and it could be a number of things, and I can’t really post code because it’s scattered throughout the project… but any ideas why this could be happening? Any quirks to using coroutines in unity that might be responsible for this?

if you use a non WaitForSeconds() return, then it will have problems with the duration. Also, if a coroutine have an error, it will stops there.

Hello there,

You definitely should post code though. There is no way we can help you if we don’t know what’s wrong.

Regardless, here is a standard Coroutine that I use for moving objects around.

    private IEnumerator MoveToTarget_OverTime(GameObject targetObj, Vector3 targetPos, float duration)
        float timer = 0.0f;
        Vector3 startPos = targetObj.transform.position;

        while (timer < duration)
            timer += Time.deltaTime;
            float t = timer / duration;
            t = t * t * t * (t * (6f * t - 15f) + 10f); // smoothing - remove if you don't want it.
            targetObj.transform.position = Vector3.Lerp(startPos, targetPos, t);

            yield return null;

Pass it the object you want to move, the position it should move to, and the duration it should move for, and you’re good to go.

Hope that helps!