Random timers in a 2d game

I have a game object that every couple of seconds i want it to change to change state, then the timer starts again and the loop is repeated till the game is closed. I got the sprite switching animation working but i cant find a solution to this sort of timer.

Thanks in advance

Hi @Swize!
There are a couple of ways you can approach this problem. I will tell you the easiest way.

Use InvokeRepeating.

InvokeRepeating is a function that keeps on calling a certain function after every x-seconds.
This is the 1 to the scripting reference.

Use this as a reference to achieve the desired effect.

I would suggest calling InvokeRepeating in the Start function (like they do in the example).

The InvokeRepeating function takes 3 parameters.

  1. Name of the function that is to be called.
  2. Delay for calling the function for the first time.
  3. After the first call to function what should be the time interval.

Feel free to ask me any other questions you have!

private float timer = 0 ;
public float Duration = 10;
public float Steps = new float{2, 4, 6, 8};
private int stepIndex ;

private void Update()
     timer += Time.deltaTime ;
     if( timer > Duration )
           timer = 0 ;
           stepIndex = 0 ;
           // Timer has looped : do something
     else if( stepIndex < Steps.Length && timer > Steps[stepIndex] )
           stepIndex++ ;
          // Step : do something