Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

play audio when light is on

Discussion in 'Scripting' started by KingaO, May 2, 2018.

  1. KingaO

    KingaO

    Joined:
    Apr 16, 2018
    Posts:
    19
    Hello,


    Im tring to write a script to enable and disable light. What I want is to turn the light on and play audio.
    It's working without second "testLight.enabled = !(testLight.enabled);". but without it Im playing audio when light is turn on and off and I want it to play only when its on. When I put second"testLight.enabled = !(testLight.enabled);" the light is not turning off at all but the audio is playing.

    Code (CSharp):
    1.  public Light testLight;
    2.     public AudioClip alarm;
    3.     AudioSource audio;
    4.     // Use this for initialization
    5.     void Start()
    6.     {
    7.         audio = GetComponent<AudioSource>();
    8.         testLight = GetComponent<Light>();
    9.         StartCoroutine(Flashing());
    10.     }
    11.  
    12.  
    13.  
    14.  
    15.     IEnumerator Flashing()
    16.     {
    17.         int time = 0;
    18.         yield return new WaitForSeconds(1f);
    19.         while (time <6)
    20.         {
    21.          
    22.             testLight.enabled = !(testLight.enabled);
    23.             audio.PlayOneShot(alarm);
    24.             yield return new WaitForSeconds(3f);
    25.             testLight.enabled = !(testLight.enabled);
    26.  
    27.             print(Time.time);
    28.             time++;
    29.         }
    30.  
    31.     }
     
  2. KingaO

    KingaO

    Joined:
    Apr 16, 2018
    Posts:
    19
    I think I know what I did wrong, I should have use another WaitForSeconds:
    Code (CSharp):
    1. testLight.enabled = !(testLight.enabled);
    2.             audio.PlayOneShot(alarm);
    3.             yield return new WaitForSeconds(3f);
    4.             testLight.enabled = !(testLight.enabled);
    5.             yield return new WaitForSeconds(3f);
     
  3. Mokzen

    Mokzen

    Joined:
    Oct 10, 2016
    Posts:
    102
    You also don't need to put your !testLight.enabled in parentheses. :)
     
  4. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583