- Home /
Waitforseconds vs Time
Ok so my first question.
Since Im developing for mobile I want to optimize as much as posible.
I got two different ways of implementing a solution and wanted to know what is better.
The problem is this, I have Function 1, Function 2 .... Function n, each function its called each "n" seconds.
I wanted to know which solution is best A (with yield WaitForSeconds) or B (using Time)
Code A
private var waitFunction01 = false;
private var waitFunction02 = false;
function Update ()
{
if(!waitFunction01)
Function01();
if(!waitFunction02)
Function02();
}
function Function01()
{
waitFunction01 = true;
Debug.Log("Function01 is running");
//other code
yield WaitForSeconds(3.0);
waitFunction01 = false;
}
function Function02()
{
waitFunction02 = true;
Debug.Log("Function02 is running");
//other code
yield WaitForSeconds(2.0);
waitFunction02 = false;
}
Code B
private var startFunction01 = 0.0;
private var startFunction02 = 0.0;
function Update ()
{
if(Time.time - startFunction01 > 3.0)
Function01();
if(Time.time - startFunction02 > 2.0)
Function02();
}
function Function01()
{
Debug.Log("Function01 is running");
//other code
startFunction01 = Time.time;
}
function Function02()
{
Debug.Log("Function02 is running");
//other code
startFunction02 = Time.time;
}
I find Code A to be "cleaner" and more precise, but I really want to hear what you guys think.
Thanks, Gustavo
Answer by Noah-1 · Oct 21, 2012 at 02:51 AM
I would use Time, as stated in UnityGems, coroutines are complicated overkill if you just want something to happen in the future, check it out, it might help:
thanks men that link is really useful, I had no idea about the invoke function.
Answer by Uniity3D · Oct 21, 2012 at 04:52 AM
Code "A" looks cleaner as you stated, but coroutines are often FPS dependant WaitForSeconds is limited by the framerate, as they're checked once per frame loop so I would go with code B.
Update is, by definition, only checked once per frame, so there is no difference in accuracy.