- Home /
Get an object to play a sound if player rolls over a trigger.
enter code here
Hi everyone. I am trying to get a sound to play when the player rolls over a seperate trigger. For this i have two scripts.
script 1 is attached to the trigger.
static var istriggered = false;
function OnTriggerEnter ()
{
istriggered = true; //sends to script 2
}
script 2 is attached to the speaker object.
var audio = audioClip
function Update ()
{
if(script1.istriggered == true)
{
audio.play("audio");
}
}
it doesnt work properly, i hear a ghost sound even before the player rolls over the trigger. Any help is appreciated. Thanks.
I'm not sure why you'd hear a sound before the player touches the trigger; for that, you might add some debug output in your OnTriggerEnter() function to see whether the two events are in sync or not. That said, as is, your code will simply attempt to start playback of the sound repeatedly once the trigger has been entered. Try adding the line 'script1.istriggered = false' before or after the line 'audio.play("audio");', and see if that makes any difference.
Answer by jtbentley · Sep 13, 2010 at 11:19 PM
That will trigger constantly once that boolean is set to true. Either add an additional boolean inside your code here...
function Update ()
{
if(script1.istriggered == true && !hasTriggered)
{
audio.play("audio");
hasTriggered = true; // So it'll only play once - you might then want to release this again
}
}
However, I think you'd be better off just calling a routine to play the sound...
function OnTriggerEnter () { if (!hasTriggered) playSound(); // Only play if the trigger has been released }
function playSound() { audio.PlayOneShot(whatever); yield WaitForSeconds(timeUntilCanPlayAgain); hasTriggered = false; }
Thanks for this, im sure that this will work to solve my problem.
Answer by · Sep 13, 2010 at 11:28 PM
You don't need to store a static variable on the trigger script, and constantly check if it's true on the speaker script. As Jesse Anders pointed out, your code will continue to play the sound. All you need to do:
Script 1 (attached to the trigger)
var speaker : Transform;
function OnTriggerEnter () { if ( speaker && !speaker.audio.isPlaying ) speaker.audio.Play(); }
Link the speaker object to the script on the trigger object, and it will check if the sound is already playing before setting it to play.
As for hearing a 'ghost sound' before the player "rolls over the trigger" - I assume the ghost sound is the audio you want to play? OnTriggerEnter will fire when the Colliders touch at all (i.e. when the exterior bounding box of the player intersects with the furthest extent of the trigger box). You could add a Debug.Log("INSIDE THE TRIGGER"); to your OnTriggerEnter to see exactly when that occurs.