TimeSince

Here’s a little utility script for Unity. Since I made it I’ve used it a few times in my prototype, so thought I’d share.

It’s basically a way to get the time since something happened, made to be a member of a class/component. It’s so simple that I’m guessing it already exists in a form that I’ve missed.

using UnityEngine;

public struct TimeSince
{
    float time;

    public static implicit operator float(TimeSince ts)
    {
        return Time.time - ts.time;
    }

    public static implicit operator TimeSince(float ts)
    {
        return new TimeSince { time = Time.time - ts };
    }
}

It’ll act like a float, but it’ll change over time.

    TimeSince ts;

    void Start()
    {
        ts = 0;
    }

    void Update()
    {
        if ( ts > 10 )
        {
            DoSomethingAfterTenSeconds();
        }
    }

It’s a struct so it doesn’t create garbage.

4 thoughts on “TimeSince

  1. I normally store a DateTime and manually compare. I wasn’t even aware of Time.time, gonna have to start using that as it’s probably more efficient. Will probably just use this whole thing you posted at some point, thanks.

    I think the “official” way you’re supposed to do this sort of things is with coroutines. The code will look a lot nicer for sure:

    private IEnumerator Something() {
    yield return new WaitForSeconds(10);
    // do things after 10 seconds.here
    }

    private void Start() { // or whatever
    this.StartCoroutine(this.Something());
    }

    I find this more readable than polling in Update(). Plus if it gets more complicated than one check doing it in Update() can get messy really quickly.

  2. Time.time scales with game time, DateTime is real world time. There’s probably not much difference if you’re not pausing/scaling your time, but worth keeping in mind.

    Coroutines work, but I don’t really like them for general stuff. Like you can use a coroutine or Invoke, but if something happens in the meantime and you want to cancel those things it’s pretty high maintenance. Having the seconds since something happened is useful for things like lerp’ing colours, animations and shit too.

  3. Co-routines are for scrubs for sure, they’re like threads but not even slightly so therefore they’re shit. Garry is right about being high maintenance, I’d much rather have a nice Timer class or something simple like this script.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s