Search Unity

Cheap way to record time passed?

Discussion in 'Scripting' started by Happy_Jingle, Apr 5, 2017.

  1. Happy_Jingle

    Happy_Jingle

    Joined:
    Mar 9, 2014
    Posts:
    103
    I want to have 100s of objects that each do something every 5 seconds since their creation. I just need a rough approximation of the time passed
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    First question regarding pretty much any performance code: Have you profiled to confirm that (X) is actually the source of your slowdown?

    If so, and this is something you do need to optimize:

    If you have hundreds of objects, then you probably want a manager class, and to remove Update() etc from the script running on the child objects. Every time Unity calls an Update() function there's a little overhead. In small numbers this doesn't matter, but when you get into hundreds it can start to. The manager class would have its own Update(), and it should have an array of the child objects that it loops through on its own; this should eliminate Update()-related overhead.

    Additionally, you don't need to (for example) add Time.deltaTime to anything every frame - you can simply set a "nextTriggeredAt" float by using Time.time + someInterval. Check Time.time each frame and you're good.
     
  3. Happy_Jingle

    Happy_Jingle

    Joined:
    Mar 9, 2014
    Posts:
    103
    This game is quite bare bones, so yes I'm sure this is the issue, for some reason when doing things in the way you suggest it's slightly more cpu intensive than just having the objects individually manage time passed using time.deltatime, do you have any other suggestions?
     
  4. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    This is one of those jobs where you take the responsibility for updating off the individual object and onto a manager class instead. The manager then can do things like update the whole lot in one go every game tick, and so the individual objects do not need to track their time at all. There is only manager time and everything gets updated once per second or some interval.

    When you're at a situation like this just use a manager to do the work not the individual.
     
  5. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    No no no. The issue could be in many different places, and you've decided it's this one with no evidence. Use the profiler window to find the problem.