Skip to content

Instantly share code, notes, and snippets.

@Ryxali
Last active March 11, 2022 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ryxali/b696607c1abb067646e4a359889682bf to your computer and use it in GitHub Desktop.
Save Ryxali/b696607c1abb067646e4a359889682bf to your computer and use it in GitHub Desktop.
Tracking time in Unity
/// <summary>
/// Keeps track of elapsed time, and is able to pause, resume & seek.
/// It's bound to Time.time, so time scaling will affect this.
/// </summary>
public struct Stopwatch
{
/// <summary>
/// How much time has passed for this stopwatch
/// </summary>
public float Elapsed => Time.time - epoch - (pausedEpoch > 0f ? (Time.time - pausedEpoch) : 0f);
private float epoch;
private float pausedEpoch;
/// <summary>
/// Create a new stopwatch. If you don't use this method for construction the stopwatch will
/// be counting from the start of the game.
/// </summary>
/// <returns></returns>
public static Stopwatch Create() => new Stopwatch
{
epoch = Time.time,
pausedEpoch = 0f
};
/// <summary>
/// Pause the stopwatch. Time will not progress for it until it's resumed
/// </summary>
public void Pause()
{
if (pausedEpoch > 0f)
epoch += Time.time - pausedEpoch;
pausedEpoch = Time.time;
}
/// <summary>
/// Make time progress for this stopwatch again
/// </summary>
public void Resume()
{
if (pausedEpoch > 0f)
epoch += Time.time - pausedEpoch;
pausedEpoch = 0f;
}
/// <summary>
/// Start counting from zero or optionally a set point
/// </summary>
public void Reset(float startFrom = 0f)
{
epoch = Time.time - Mathf.Max(0f, startFrom);
pausedEpoch = pausedEpoch > 0f ? Time.time : 0f;
}
/// <summary>
/// Modify elapsed by this amount. The resulting time will not become negative
/// </summary>
/// <param name="amount"></param>
public void Seek(float amount)
{
epoch -= amount;
epoch += Elapsed < 0 ? Elapsed : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment