- Home /
On trigger enter play sound problem
Hello Unity answer community,
I trying to trigger a sound once a player enters a trigger it works but im having some problem, the sound will start when the game starts up but it still plays when the player triggers it and it does not play one, every time the player walks into the trigger the sound will play.
Things i need help with
1) play sound only once
2) stop sound from playing when game is started only play sound when trigger is entered
Here is what my script looks like :
#pragma strict
var flashClip:AudioClip;
var isFlash = false;
function OnTriggerEnter (o:Collider) {
Debug.Log("The Trigger fired enter");
isFlash = true;
}
function OnTriggerExit (o:Collider){
Debug.Log("the trigger fired");
if(isFlash == true) {
playFlash ();
}
}
function playFlash () {
audio.PlayOneShot(flashClip);
isFlash = false;
}
Thank you for taking your time, Have a nice day/night.
Answer by dorpeleg · Feb 05, 2013 at 09:47 PM
Look at your audio source, it might be set to play on awake.
Set isFlash defult value to true.
Remove isFlash = true; from the OnTriggerEnter funcation.
Move if(isFlash == true) { playFlash (); } to the OnTriggerEnter funcation.
No need for OnTriggerExit funcation.
Answer by AndrewGrayGames · Feb 05, 2013 at 10:06 PM
One other question to consider - how are you sure it's the player that is entering your trigger?
What I usually do for a trigger that only responds to the player is the following:
public void OnTriggerEnter(Collider who)
{
if(who.tag != "Player")
return;
// ...From here, along the lines of what previous answerers have responded...
}
To make it work, I ensure that player is tagged as...well, a "Player" in the editor. That way, if the terrain enters your trigger (or a bullet...or an enemy...or an item), your one-shot sound won't fire.
Your answer
Follow this Question
Related Questions
OnTriggerEnter problem 3 Answers
Triggering random sound on player 1 Answer
Totally new noob to mecanim and unity itself - Trigger animation? 0 Answers
On trigger , sound play 2 Answers