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): 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: Code (CSharp): testLight.enabled = !(testLight.enabled); audio.PlayOneShot(alarm); yield return new WaitForSeconds(3f); testLight.enabled = !(testLight.enabled); yield return new WaitForSeconds(3f);
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. https://docs.unity3d.com/ScriptReference/AudioSource.PlayDelayed.html