Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Conceptualising a timer script

Discussion in 'Scripting' started by kittik, Oct 9, 2015.

  1. kittik

    kittik

    Joined:
    Mar 6, 2015
    Posts:
    565
    For my current project I will need a script that can simulate time elapsing and years will have to go by.

    To do this I am thinking that on every update or fixed update, +1 to a count should happen and for every X (let's say 3600) counts a year is added. This could also look at for each 300 counts a month has elapsed. When each year elapses it will then call other scripts that will only be called when a year has taken place.

    I wanted to ask whether you feel that I am looking at this correctly, if Update or Fixed Update is the right place to put this code and if a foreach loop or an infinite loop would be the best place to handle the code?
     
  2. martinmr

    martinmr

    Joined:
    Mar 25, 2015
    Posts:
    325
    Update would be enough.
    you don't need a foreach loop or infinte loop the "Update()" method is your infinite loop.

    What I would do is to set first 1 real second = XX ingame seconds.

    then using Time.deltaTime in update to count up an float than checking for ealpsed time. with if clauses looking for is a year or month passed.
     
    kittik likes this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Most of the the time I would suggest taking snapshots of Time.time. Compare the start time to the current time and you'll have the number of simulation seconds that have elapsed. This can then be converted to the value you need to use.

    Incrementing by Time.deltaTime every frame works. But with each frame it's subject to rounding errors. (It's also subject to floating point precision errors after about 2.5 days of running, if that matters.)
     
    martinmr and kittik like this.
  4. martinmr

    martinmr

    Joined:
    Mar 25, 2015
    Posts:
    325
    Also thought about Tiime.time so you have to set the time when lvl oder map is loaded as startTime, because Time.time will also give you the time form app start.

    Also depending on how you want to build your game. Only counting time when app is started and played, or even if it's off and starting the game again that this real time is also conted ito your game you have also to save date and time in savegame.

    So there are several ways we can think of but in the end you have to knpow how you will design this gamepart :)

    Happy coding