Videogames Development – Unity – Delay Execution Time

yield WaitForSeconds

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#pragma strict
 
function Start()
{
// Prints 0
print (Time.time);
// Waits 5 seconds
yield WaitForSeconds (5);
// Prints 5.0
print (Time.time);   
}
 
function Update()
{
 
}

NOTICE:
yield WaitForSeconds (5); -> yield (dare la precedenza) Aspetta per Secondi 5

Invoke

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#pragma strict
  
function Start()
{
    // Invoke (function name, delay time in seconds)
    Invoke ("myFunction", 2);
    Invoke ("myFunctionTwo", 4);
}
     
function myFunction()
{
    Debug.Log("Delay time of 2 seconds");
}
 
function myFunctionTwo()
{
    Debug.Log("Delay time of 4 seconds");
}

Invoke Repeat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#pragma strict
  
var x: int;
 
function Start()
{
    // InvokeRepeiting (function name, delay time in seconds, repeat every x seconds...)
    InvokeRepeating("myFunction", 2, 1);
}
 
function myFunction()
{
    var x = x++;
    Debug.Log("Invoked " + x);
}

The result is:

Invoked 0
Invoked 1
Invoked 2
Invoked 3
… to infinity and beyond!