0
\$\begingroup\$

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();
            }
        }

    }
}
\$\endgroup\$
9
  • \$\begingroup\$ 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 \$\endgroup\$
    – Henry
    Jun 3 at 0:58
  • \$\begingroup\$ just select it all, and press the {} button above the text box, that'll help =) \$\endgroup\$
    – Millard
    Jun 3 at 1:03
  • \$\begingroup\$ 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? \$\endgroup\$
    – Millard
    Jun 3 at 1:04
  • 2
    \$\begingroup\$ Where do you change the value of flashlightisoff? \$\endgroup\$
    – DMGregory
    Jun 3 at 1:22
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Millard
    Jun 3 at 4:46
2
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ it worked thanks ShoulO! \$\endgroup\$
    – Henry
    Jun 6 at 16:11
  • \$\begingroup\$ Glad to hear that ! \$\endgroup\$
    – ShoulO
    Jun 6 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.