Unity – Repeiting a function

Invoke Repeat

#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!

Cancel Invoke

        // Starting in 2 seconds.
	// a projectile will be launched every 0.3 seconds
	var projectile : Rigidbody;
	InvokeRepeating("LaunchProjectile", 2, 0.3);

	// Cancels the repeating invoke call, 
	// when the user pressed the ctrl button
	function Update() {
		if (Input.GetButton ("Fire1"))
			CancelInvoke("LaunchProjectile");
	}
	function LaunchProjectile () {
		instance = Instantiate(projectile);
		instance.velocity = Random.insideUnitSphere * 5;
	}