- Home /
Countdown Timer or WaitForSeconds?
Hey Everyone,
I'm currently writing a script where I want to instantiate a game object randomly. I am planning to deploy the game on mobile and was wondering if I should use a countdown timer or WaitForSeconds instead?
If you were in my shoes, which one would you consider using and why would you use it?
Thanks, Beeraj
private float Timer = 5.0f;
if(Timer > 0)
{
Timer -= Time.deltaTime;
}
if(Timer <= 0)
{
Debug.Log("Execute Instantiate Script");
}
this is fine. but i would definatly recommend using Time.fixedDeltaTime incase frame rate fluctuates. could also put it in fixedUpdate func
@$$anonymous$$larax - You would only want to use 'fixedDeltaTime' if you were executing this code in FixedUpdate(). Using 'fixedDeltaTime' in Update() would cause havoc in the ti$$anonymous$$g.
@$$anonymous$$larax - For a one-off spawn, consider Invoke(). For repeated, non-interrupted spawns, consider a Coroutine and WaitForSeconds(), or what you have here is fine.
Answer by senc01a · Aug 26, 2014 at 01:30 PM
I would use WaitForSeconds. This is mainly due to the feeling that the WaitForSeconds
might be more optimized. I would imagine that WaitForSeconds would trigger some kind of internal event when the time is right, instead of calculating the Timer -= Time.deltaTime;
on every update()
.
However keep in mind that this is simply due to an assumption of the underlying implementation of WaitForSeconds
, and not based in any real evidence.
On the other hand, you might trust more your code, and think that manually keeping track of the amount of time is more reliable since you don't rely on somebody else's implementation.
Last but not least, since your time decrements happen on every tick, it is very well possible that Timer is not exactly 0, but a negative number by the time your IF statement is true. That would mean that you are skipping a few milliseconds. Perhaps the WaitForSeconds
is more precise in that respect, although then again we don't really know because we don't have the implementation code.
Answer by brycem24 · Aug 26, 2014 at 01:38 PM
I would instead use the InvokeRepeating() method. You could have it so your instantiate function randomly picks one. And use the Invoke Repeating to call the instantiate method at the intervals you want to generate the game objects. So in conclusion your script should look something like this. void Start() { InvokeRepeating("methodName", delay, intervalRate); }
Your answer
Follow this Question
Related Questions
Skipping over timer 1 Answer
How to start a timer after object is not active? 1 Answer
Photon Multiplayer Countdown TImer 2 Answers
disappear script that last a certain amount of time 2 Answers