Hello. How can I have a static variable be set to a specific value after a set amount of time? I dont want to use Invoke Repeating because the values will not be based on the same formula (ex: it wont be something like "every 2 seconds add 5"). For example, after 30 seconds the value will equal 5, after 45 it will equal 20 and after 60 it will equal 15 etc. Thanks
There are several methods, but the easiest way is to have a interval variable and a timer variable. Lets say we want to trigger something every second:
var interval:float = 1; //for 1 second
var timer:float;
now:
function Start()
{
timer = Time.time + interval; //the timer is equal to the time in the future
}
function Update()
{
if(Time.time >= timer) //if the current time elapsed is equal to or greater than the timer
{
//do something
timer = Time.time + interval; //set the timer again
}
}
again, there are many ways to do it but this is a quick and dirty way I use often.
The accepted answer is a correct solution save for 1 thing…
Replace
timer = Time.time + interval; //set the timer again
with
timer += interval; //set the timer again
The problem is, as it is now, your timer will start to get inaccurate after a while, since your updates are not in exact sync with seconds. You don’t want to redefine your timer every tick, you just want to add 1 second each tick. As it is now, the slight offset of the update frequency will compound and make the timer completely inaccurate after running a few minutes.
Just needed to clear that up for anyone else using this code.