- Home /
Play Sound On Trigger Enter
Hi, i have a FPS Controller tagged "Player" and a cube with a Collider "on trigger", i want to play a sound when my "Player" touches the cube, the cube has an Audio Source component with the specific sound attached to it, but i dont know exactly how to do this on script, any help will be appreciated, thank you.
PD: Found this script on another question, but gives me an error of "semicolon missing" on line 1,5.
void OnTriggerEnter(Collider otherObj)
{
if (otherObj.tag == "player")
{
audio.Play();
}
else {
audio.Stop();
}
}
you might want to put audio.Stop(); in OnTriggerExit()
Hi everybody, its .js, javascript...i try the same script on .cs, but doesnt works...thanks for the answers!
Answer by aldonaletto · Oct 13, 2011 at 10:53 PM
This is a C# script - it should have a lot of other things declared before the first line showed above, like @DaveA suspected. If you want a JS version, it could be something like this:
function OnTriggerEnter(otherObj: Collider){ if (otherObj.tag == "Player"){ audio.Play(); } else { audio.Stop(); } }This script will start the sound when the player enters the trigger, and stop it if other object enters. If you want to stop the sound when the player leaves the trigger (like @chemicalvamp suggested), it should be:
function OnTriggerEnter(otherObj: Collider){ if (otherObj.tag == "Player"){ audio.Play(); } }
function OnTriggerExit(otherObj: Collider){ if (otherObj.tag == "Player"){ audio.Stop(); } }
...i have a issue with giving to my cube a new tag called otherObj, when i add this new tag, it dont shows up on the drop down menu, insted shows up on the Layers drop down menu, i donkt know why.....
You don't have to tag it "otherObj" - otherObj is just the variable name. Only the player must be tagged "Player" for this to work. Just leave the cube untagged.
$$anonymous$$ost objects in scene are untagged. Tags are mostly used to identify some special objects (the player, in this case) or objects of the same kind - like "Enemy", for instance.
It WOR$$anonymous$$S!, this is very nice and helpful code, i see, then its no need to tag my cube... Thank you !