Why does only the sound for turning off the flashlight play?

This script is supposed to play a sound when I turn on the flashlight sprite and a different sound when I turn it off, but for some reason it's only playing the second sound.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class flashlightonoffsound : MonoBehaviour
{
public static bool flashlightisoff = false;

public AudioSource flashlightsound1;

public AudioSource flashlightsound2;

void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (flashlightisoff)
{
flashlightsound1.Play();
}
else
{
flashlightsound2.Play();
}
}

}
}

• also idk why but the some of the code isn't in the code box when i post it for some reason but its fine you can still understand it Jun 3 at 0:58
• just select it all, and press the {} button above the text box, that'll help =) Jun 3 at 1:03
• I don't want to sound obvious, but have you checked that you don't have the same sound assigned to both variables in the inspector? Jun 3 at 1:04
• Where do you change the value of flashlightisoff? Jun 3 at 1:22
• one thing you could try, is under if (flashlightisoff) add the line: flashlightisoff = false and under else add the line: flashlightisoff = true. it depends on your flashlight code, though. I'm guessing that flashlightisoff is always false, so it's always playing the 2nd sound. Jun 3 at 4:46

First I would suggest not to use 2 AudioSources. That causes a lot of confusion. Instead use only one audiosource for one game object, and switch between audioClips:

public AudioClip clip1;
public AudioClip clip2;


and then somewhere in your logic you play the clip:

myAudioSource.PlayOneShot(clip1); // or clip2 ....


Second make sure you are changing value of flashlightisoff correctly. For example you maybe changing it ok, but next frame it reverts back (which often is mistake when people are using Input.GetKeyDown). You can track value of your variable like that:

void Update()
{
Debug.Log("value:" + flashlightisoff );
}


then watch console for what happens with your variable every frame, and you will know where fault is.

• it worked thanks ShoulO! Jun 6 at 16:11
• Glad to hear that ! Jun 6 at 19:56