Light problem

Hi to all…
I have a problem in the void Update, when I press the key the sequence doesn’t start, I have to press the key two times… And then the sequence doesn’t stop when I press the key again… I think I made a mistake in IEnumerator StopLight()
Hope someone can Help me to solve my probem :slight_smile:

public class LightAnimator : MonoBehaviour {
	// number of seconds between changing light
	public float lightTime = 1;
	// the current light that is lit.
	int currentLight = 0;
	
	public Light[] lights;
	public KeyCode controlKey = KeyCode.X;
	private bool on = false;
	

	IEnumerator ChangeLight()
	{
		
		yield return new WaitForSeconds(lightTime);   
		
		Debug.Log("Changing light to number "+currentLight);
		
		// disable the current light
		lights[currentLight].enabled = false;
		
		// change the index to the next light
		currentLight++;
		
		
		
		// if the index is 4 or more, go back to the first light
		if (currentLight >= 4)
			currentLight = 0;
		
		// the current light is now the next light, so enable it.
		lights[currentLight].enabled = true;
		
		// call this method again to create an infinite loop.
		StartCoroutine("ChangeLight");
		
	}

	IEnumerator StopLight()
	{
		yield return new WaitForSeconds(lightTime);   
		// disable the current light
		lights[currentLight].enabled = false;
		
		// call this method again to create an infinite loop.
		StartCoroutine("StopLight");

	}


	void Update(){
		
		if (Input.GetKeyDown (controlKey)) {
			on = !on;

		if (!on) {
		StartCoroutine ("ChangeLight");  
		}   
		if (on) {
		StartCoroutine ("StopLight");

			}
	}
	
}
}

do this instead:

public class LightAnimator : MonoBehaviour {
    Coroutine lightOnCoroutine;
    Coroutine lightOffCoroutine;

    void Start() {      
    }

    void Update() {
        if (Input.GetKeyDown (controlKey)) {
             on = !on;
 
         if (!on) {
             lightOnCoroutine = StartCoroutine ("ChangeLight");  
            if(lightOffCoroutine != null) {
                  StopCoroutine(lightOffCoroutine);
            }
         }   
         if (on) {
              lightOffCoroutine = StartCoroutine ("StopLight");
              if(lightOnCoroutine != null) {
                    StopCoroutine(lightOnCoroutine);
             }

 
             }
     }

     IEnumerator ChangeLight() {
          int i = 0;
          while(true) {
                  lights*.enabled = false;* 

i++;
if(i > lights.length - 1) {
i = 0;
}
lights*.enabled = true;*
yield return WaitForSeconds(1);
}
}

}
This is a rough example. The idea is to keep track of your coroutines, and do not rely on infinite recursion for them. You’ll have more control.
A better way to do this though is with a single coroutine that checks to see if a flag is set for swapping lights (instead of while(true), do while(myBool)). When you want to switch them off, just set the boolean to false, and manually turn off all the lights (no need for a coroutine to turn them off it seems).