Laser fire/stop/repeat script not working as intended

I am wanting a laser beam to fire for x amount of seconds, stop for x amount of seconds, then repeat. I have set it up so the laser activates after a fairly long delay, and while it then activates for the correct amount of time after the initial firing it keeps going on and off constantly instead of repeating my coroutine. I might have done something wrong but it looks right to me?

{
    public GameObject Laser;
    private bool Stage1;

   void Start ()

    {
        Stage1 = true;
        StartCoroutine(WaitTimer());

    }
   
   void Update ()

    {
       
           if(Stage1 == false)
        {

            Laser.active = true;
            StartCoroutine(WaitTimer2());

        }
   
    }

    private IEnumerator WaitTimer()
    {

        yield return new WaitForSeconds(115.0f);

        Stage1 = false;


    }

    private IEnumerator WaitTimer2()

    {

        yield return new WaitForSeconds(3.0f);

        Laser.active = true;

        yield return new WaitForSeconds(5.0f);

        Laser.active = false;

       



    }
}

Using coroutines for something like this is a recipe for confusion. Why not keep it simple, with something like this.

class PeriodicActivator : MonoBehaviour {
    public GameObject objectToActivate;
    public float onTime = 1;
    public float offTime = 1;
   
    void Update() {
        float totalTime = onTime + offTime;
        float t = Time.time % totalTime;
        objectToActivate.active = (t < onTime);
    }
}

Thank you so much :slight_smile: I was using a coroutine as I had done a similar sort of setup with a different script, although that one has additional stuff including a while loop which I guess is needed other it doesn’t work properly. Yours is much simpler and works perfectly :slight_smile:

1 Like