- Home /
Need help making an audio trigger.
I want an audio clip to play when the FPC enters a trigger, but the script I have won't seem to work.
Here's the script:
var Sound : AudioClip;
private var hasPlayed = false;
function OnTriggerEnter(){ if(!hasPlayed){ audio.PlayOneShot(Sound); hasPlayed = true; } } I have the script placed in the FPC, I have the audio clip placed in the inspector, and the box collider on the game object is checked as trigger. I'm still pretty new to Unity.
Answer by UnrealIzzy · Aug 07, 2012 at 11:32 AM
Here Is a quick audio Trigger I put together It's simple but does the job :D
var Trigger : AudioClip;
function OnTriggerEnter(){
audio.Play();
}
When you enter the trigger area then the audio clip you choose plays. But if you want one where you can press a button and the audio plays then use this,
var Trigger : AudioClip;
var canFire;
function OnTriggerStay(){
if (Input.GetButtonDown ("Fire1")) {
canFire=true;
audio.Play();
}else{
canFire=false;
}
}
Hope this helped :D
Answer by aldonaletto · Aug 07, 2012 at 12:04 PM
Your code should work. Does your FPC have an AudioSource? audio is the reference to the object's AudioSource, thus you must have one added to the FPC (this script's owner).
Another possibility is to use PlayClipAtPoint - this instruction creates a temporary AudioSource at the specified point, deleting it when the sound has finished:
... function OnTriggerEnter(){ if(!hasPlayed){ AudioSource.PlayClipAtPoint(Sound, transform.position); hasPlayed = true; } }Additionally, you should check if the FPC entered the right trigger before playing the sound (believe me, you'll probably will have other triggers in your scene):
... function OnTriggerEnter(other: Collider){ // verify if this is the sound trigger (named "SoundTrigger" here): if(other.name == "SoundTrigger" && !hasPlayed){ AudioSource.PlayClipAtPoint(Sound, transform.position); hasPlayed = true; } }