x


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.

more ▼

asked Aug 07 '12 at 10:37 AM

KinnisHorizon gravatar image

KinnisHorizon
1 2 4

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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

more ▼

answered Aug 07 '12 at 11:32 AM

UnrealIzzy gravatar image

UnrealIzzy
64 6 8 13

(comments are locked)
10|3000 characters needed characters left

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;
  }
}
more ▼

answered Aug 07 '12 at 12:04 PM

aldonaletto gravatar image

aldonaletto
41.3k 16 42 195

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1944
x1684
x1026
x981
x523

asked: Aug 07 '12 at 10:37 AM

Seen: 431 times

Last Updated: Aug 07 '12 at 12:04 PM