Is it possible to repeat a script?

Is it possible to repeat a script? I hope there is. If you know, tell me :slight_smile:

This is the script that I want to repeat (forever)

var Light1 : Light;

function Start () 
{
	Light1.enabled = true;
	yield WaitForSeconds(2);
	Light1.enabled = false;
	yield WaitForSeconds(2);
}

You can use one of the three basic loop functions languages such as this provide.

The ‘while’ loop:

The ‘while’ loop executes the code in the brackets as long as the expression x is true.

while(x){
  //do your things
}

Example:

a=1;
while(a<4){
  a++;
}

This will run until a equals 4.


The ‘do-while’ loop:

The do-while loop is almost identical to the while loop. The key difference is that the expression checking is done at the end, so the code is guaranteed to run at least once.

do{
  //code
}while (x)

The ‘for’ loop:

The ‘for’ loop is a bit more complicated. Its syntax is as follows:

for(x;y;z){
  //code here
}

In this instance:

  • X is a piece of code that will be executed before the loop starts.
  • Y is the boolean expression that is checked to see whether the loop will continue
  • Z is a piece of code that is executed at the end of each repetition.

Either one of these can be omitted, therefore for(;;){ } is valid.
A C++ programming joke was to #define EVER ;; and then using

for(EVER){  }

Example:

for(var i:int=0;i<10;i++){
  Debug.Log(i); //This will print you all the numbers from 0 to 9.
}

In your particular case:

while:

while(true){
  Light.enabled=false;
  yield WaitForSeconds(2);
  Light.enabled=true;
  yield WaitForSeconds(2);
}

do-while:

do{
  Light.enabled=false;
  yield WaitForSeconds(2);
  Light.enabled=true;
  yield WaitForSeconds(2);
}while(true)

for:

for(;;){
  Light.enabled=false;
  yield WaitForSeconds(2);
  Light.enabled=true;
  yield WaitForSeconds(2);
}

Keep in mind though. The usage of yield turns the function this is called in to a coroutine. You can’t use yield statements in Update, or similar functions.

Just put an infinite loop, if that’s what you mean by repeating a script.

function Start ()
{
   while (true)
   {
      Light1.enabled = true;
      yield WaitForSeconds(2);
      Light1.enabled = false;
      yield WaitForSeconds(2);
   }
}