Search Unity

Laser fire/stop/repeat script not working as intended

Discussion in 'Scripting' started by serbusfish, Aug 18, 2017.

  1. serbusfish

    serbusfish

    Joined:
    Dec 27, 2016
    Posts:
    247
    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?

    Code (csharp):
    1.  
    2. {
    3.     public GameObject Laser;
    4.     private bool Stage1;
    5.  
    6.    void Start ()
    7.  
    8.     {
    9.         Stage1 = true;
    10.         StartCoroutine(WaitTimer());
    11.  
    12.     }
    13.    
    14.    void Update ()
    15.  
    16.     {
    17.        
    18.            if(Stage1 == false)
    19.         {
    20.  
    21.             Laser.active = true;
    22.             StartCoroutine(WaitTimer2());
    23.  
    24.         }
    25.    
    26.     }
    27.  
    28.     private IEnumerator WaitTimer()
    29.     {
    30.  
    31.         yield return new WaitForSeconds(115.0f);
    32.  
    33.         Stage1 = false;
    34.  
    35.  
    36.     }
    37.  
    38.     private IEnumerator WaitTimer2()
    39.  
    40.     {
    41.  
    42.         yield return new WaitForSeconds(3.0f);
    43.  
    44.         Laser.active = true;
    45.  
    46.         yield return new WaitForSeconds(5.0f);
    47.  
    48.         Laser.active = false;
    49.  
    50.        
    51.  
    52.  
    53.  
    54.     }
    55. }
    56.  
    57.  
    58.  
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Using coroutines for something like this is a recipe for confusion. Why not keep it simple, with something like this.

    Code (CSharp):
    1. class PeriodicActivator : MonoBehaviour {
    2.     public GameObject objectToActivate;
    3.     public float onTime = 1;
    4.     public float offTime = 1;
    5.    
    6.     void Update() {
    7.         float totalTime = onTime + offTime;
    8.         float t = Time.time % totalTime;
    9.         objectToActivate.active = (t < onTime);
    10.     }
    11. }
     
  3. serbusfish

    serbusfish

    Joined:
    Dec 27, 2016
    Posts:
    247
    Thank you so much :) 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 :)
     
    JoeStrout likes this.