Hey!
I have a case where a game is paused using Time.timeScale = 0.0f;
, but various pieces of code that are usually run on update (code related to rendering) and fixed update (code related to physics) should still run.
- What would be a correct way to achieve this?
- Is there a way to make physics work with timeScale set to 0? (see example 2. below)
So far I have been trying to do this using coroutines, here are 2 examples for Update and FixedUpdate:
- Here is an example of a coroutine that sets a light’s intensity from 0 to 1 in 10s in sync with the frame rate (which would usually be achieved by running code in
Update
or in a coroutine usingTime.deltaTime
andyield return null
):
private IEnumerator MyCustomUpdate()
{
// Initialize
Light light = GetComponent<Light>();
float timer = 0.0f;
float duration = 10.0f;
// Run animation
while (timer < duration)
{
light.intensity = timer / duration;
timer += Time.unscaledDeltaTime;
yield return new WaitForEndOfFrame();
}
}
- The same could be done with code related to physics, but there I doubt this would actually work as physics updates are no longer performed since
Time.timeScale
is 0? So this piece of code would allow my rigidbody to be moved while the game is paused, but no physics interaction (OnCollisionEnter
,OnTriggerEnter
, etc.) would occur, right?
private IEnumerator MyCustomFixedUpdate()
{
// Initialize
Rigidbody myRigidbody = GetComponent<Rigidbody>();
float movingSpeed = 1.0f;
// Run animation
while (Time.timeScale == 0.0f)
{
Vector3 force = Time.fixedUnscaledDeltaTime * movingSpeed * movingInput; // Assuming that movingInput is a vector set somewhere else using the input system
myRigidbody.AddForce(force);
yield return new WaitForEndOfFrame();
}
}
Thanks for your help!