play audio when light is on

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.

 public Light testLight;
    public AudioClip alarm;
    AudioSource audio;
    // Use this for initialization
    void Start()
    {
        audio = GetComponent<AudioSource>();
        testLight = GetComponent<Light>();
        StartCoroutine(Flashing());
    }




    IEnumerator Flashing()
    {
        int time = 0;
        yield return new WaitForSeconds(1f);
        while (time <6)
        {
          
            testLight.enabled = !(testLight.enabled);
            audio.PlayOneShot(alarm);
            yield return new WaitForSeconds(3f);
            testLight.enabled = !(testLight.enabled);

            print(Time.time);
            time++;
        }

    }

I think I know what I did wrong, I should have use another WaitForSeconds:

testLight.enabled = !(testLight.enabled);
            audio.PlayOneShot(alarm);
            yield return new WaitForSeconds(3f);
            testLight.enabled = !(testLight.enabled);
            yield return new WaitForSeconds(3f);

You also don’t need to put your !testLight.enabled in parentheses. :slight_smile:

Just as a note, there’s a command specifically for audio that you can use to delay so you don’t need to necessarily use WaitForSeconds or a Coroutine, it’s called PlayDelayed.