- Home /
Audio not playing
I have an issue, where the audio wont play. its on a spot light object inside a camera. the spot light has the following script and has audio source components and the player object (houses the camera) has a audio listener. YET I HEAR NO SOUND...
using UnityEngine;
using System.Collections;
public class torchscript : MonoBehaviour {
public bool on = false;
public AudioClip FlashOff;
void Update()
{
if(Input.GetKeyDown(KeyCode.F))
on = !on;
if(on)
light.enabled = true;
else if(!on)
light.enabled = false;
audio.PlayOneShot(FlashOff, 0.7F);
}
}
i know theres been a lot of problems with this for people before..
Answer by ArkaneX · Jan 06, 2014 at 01:26 AM
I think the problem is that you call PlayOneShot outside of your if
. So it is effectively called 60 times a second (assuming your game runs at 60FPS). Please include it inside of the if
statement by introducing curly brackets:
if(on)
{
light.enabled = true;
}
else
{
light.enabled = false;
audio.PlayOneShot(FlashOff, 0.7F);
}
Of course only curly brackets after else
are necessary. The pair after if
can be omitted, but I strongly suggest to always use them - this IMO makes your code more readable. Besides, there's no need to use
else if(!on)
because in this case just else
is enough.
ok so it seems to work now. kind of. It does play in the editor but when i compile and play it, it does... YET it plays constantly from the launch of the game.. idk why..
Did you encapsulate it all within the Get$$anonymous$$eyDown statement? If not, that would be why, since it doesn't need to meet that condition to check if the light is off and play the audio. But you can simplify the code even more like this.
void Update()
{
if ((Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.F)) && (!on))
{
on = true;
light.enabled = true;
}
else if((Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.F)) && (on))
{
on = false;
light.enabled = false;
audio.PlayOneShot(FlashOff, 0.7F);
}
}
You could make it even simpler by getting rid of the "on" bool and just using "light.enabled in the conditions above.
Your answer
Follow this Question
Related Questions
How to convert a 2d sound to a 3d sound in script? 0 Answers
Unity 5 Audio Source volume falloff for mono sound without panning 0 Answers
How can I improve OGG music quality? 1 Answer
Background music lowers when I use AudioSource.PlayClipAtPoint() 1 Answer
Control Mono/Stereo via Audio Mixer? 0 Answers