# Coroutine stops when Time.timeScale = 0

I have a coroutine that smoothly changes a variable in my UI, but when I pause the game, the coroutine pauses too. How can I fix that?

Code:

using UnityEngine;
using System.Collections;

public class HUDController : MonoBehaviour {
public void PauseGame() {
FreezeTime();
}

private void FreezeTime() {
Time.timeScale = 0;
}

var alphaValue = 1f;
var velocity = 0f;
var time = 0.15f;

yield return null;
}

pauseMenuCanvasGroup.alpha = 1; // Since float is not accurate, manually set the alpha to 1
}
}

• I'm unable to reproduce this issue in Unity 5. In my tests, coroutines that yield return null or new WaitForEndOfFrame() keep humming along just fine when Time.timeScale = 0 - it's only yield return new WaitForSeconds(delay) that pause. Can you confirm what version of Unity you're running? – DMGregory Jan 10 '16 at 14:00
• @DMGregory 5.2.3f1 – Milen Jan 10 '16 at 14:01
• How sure are you that the timescale is the cause? Have you tried to not set the timescale to zero and still run the coroutine? – Athos vk Jan 10 '16 at 14:09
• Yes, I removed the timescale and it runs just fine – Milen Jan 10 '16 at 14:42
• Can anyone help? – Milen Jan 10 '16 at 18:59

This is sure to happened because Mathf.SmoothDamp uses Time.deltaTime in default calculation. When you set Time.timeScale = 0 then Mathf.SmoothDamp won't give the expected value but only first value, repeatedly.

You can further verify by printing alpha value to console, print it in your while loop so that you can confirm it by the unlimited logs of same value.

Here is the Documentation on Mathf.SmoothDamp.

You can fix this by passing your own deltaTime to keep it from using its default Time.deltaTime. Just add one more parameter to the end of the call:

pauseMenuCanvasGroup.alpha = Mathf.SmoothDamp(
alphaValue,
ref velocity,
time,
1000,          // <-- Fifth parameter Optionally allows you to clamp the maximum speed.