Skip to content

Instantly share code, notes, and snippets.

@winkels
Last active December 21, 2022 12:10
Show Gist options
  • Save winkels/9770101 to your computer and use it in GitHub Desktop.
Save winkels/9770101 to your computer and use it in GitHub Desktop.
Unity script that allows for updates while Time.timeScale = 0. See http://www.asteroidbase.com/?p=569 for context.
using UnityEngine;
using System.Collections;
public class TimeScaleIndependentUpdate : MonoBehaviour
{
//inspector fields
public bool pauseWhenGameIsPaused = true;
//private fields
float previousTimeSinceStartup;
protected virtual void Awake()
{
previousTimeSinceStartup = Time.realtimeSinceStartup;
}
protected virtual void Update()
{
float realtimeSinceStartup = Time.realtimeSinceStartup;
deltaTime = realtimeSinceStartup - previousTimeSinceStartup;
previousTimeSinceStartup = realtimeSinceStartup;
//It is possible (especially if this script is attached to an object that is
//created when the scene is loaded) that the calculated delta time is
//less than zero. In that case, discard this update.
if(deltaTime < 0)
{
Debug.LogWarning("Delta time less than zero, discarding (delta time was "
+ deltaTime + ")");
deltaTime = 0;
}
//NOTE: You will want to change "GameStateManager.SharedInstance.Paused()"
//to whatever you use to check if the game has been paused by the user
if(pauseWhenGameIsPaused && GameStateManager.SharedInstance.Paused())
{
deltaTime = 0;
}
}
public IEnumerator TimeScaleIndependentWaitForSeconds(float seconds)
{
float elapsedTime = 0;
while(elapsedTime < seconds)
{
yield return null;
elapsedTime += deltaTime;
}
}
#region Property methods
public float deltaTime { get; private set; }
#endregion
}
@DataGreed
Copy link

Omg, looking for a solution to a problem and found it in the devlog for one of my favourite games! Thanks <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment