- Home /
Using Time.deltaTime as time counter.
Recently I faced a little problem. In my game (and I'm pretty sure in yours too) I use this construction very often:
void Update()
{
sinceLastAction += Time.deltaTime;
if (sinceLastAction > actionTimeout)
{
DoAction();
sinceLastAction = 0;
}
}
But when actionTimeout
has low float value (like 0.5 or 0.1) you can stuck in situation when Time.deltaTime
has half or even greater value of your time counter (especially when you manipulate with Time.timeScale
), and it's bring problem when part of your time just get deleted each Update()
. Other example, your game got lag or something and Time.deltaTime
pretty high, in some cases you can have more then one not executed actions. So is my question, should I use constructions like this:
void Update()
{
sinceLastAction += Time.deltaTime;
if (sinceLastAction > actionTimeout)
{
int timesActionHappend = Mathf.FloorToInt(sinceLastAction/actionTimeout);
for (int i = 0; i < timesActionHapped; i++)
DoAction();
sinceLastAction -= actionTimeout * timesActionHappend;
}
}
, or I just misunderstanding some basic principles of time based programming?
Answer by Bunny83 · May 23, 2013 at 09:45 AM
This can be simplified to:
void Update()
{
sinceLastAction += Time.deltaTime;
while (sinceLastAction > actionTimeout)
{
DoAction();
sinceLastAction -= actionTimeout;
}
}
ye, you right! Thanks! Is there any possibilities to not write this constructions each time I want to create simple timer? Like this:
public float attackTimeout;
void Awake()
{
Timer.Add(attackTimeout, Attack);
}
public void Attack()
{
//stuff
}
Sure! I'm wondering where Fattie is ;) He always tries to force everyone to use InvokeRepeating ;)
InvokeRepeating is nice, but problems starts when you'll try to save state of invocation, ex.: when you want save to file, you can just write sinceLastAction
variable, and then read it, but when you use Invoke family methods, I have no idea how to store state of invocation. If you have any thoughts about it, please tell me ;)