Playing sound on collide with a trigger.

I created an empty object and named it “soundtrigger1” Now i used the script which i found on another question.

function OnTriggerEnter(otherObj:
Collider){
if (otherObj.tag == “Graphics”){
audio.Play();
}
else {
audio.Stop();
}
}

The “Graphics” is the actual player on the First Person controller script which comes with Unity standard assets. I have attached a box collider to the empty object and made it a trigger. I attached a sound to the object aswell so when the “Graphics” collides with it, it will play a sound.
This doesnt work…
Is there another way to make sound play on collision? i have been researching this for a long time and couldn’t find the answer i was looking for.
Thanks for your time.

try this simple script

var soundFile:AudioClip;
 
function OnTriggerEnter(trigger:Collider) {
     if(trigger.collider.tag=="Player") {
        audio.clip = soundFile;
        audio.Play();
     }
}

Things to check:

  • In Edit > Project Settings > Physics, make sure that the layers assigned to your first person controller and soundtrigger1 are set to register collisions (checkbox is ticked).

  • Double-check that the first person controller object has a collider, and that this object’s tag is really “Graphics” (with exact capitalization).

  • You probably don’t need “audio.Stop()”. This might be causing a problem if another collider (perhaps on a child object of the first person controller) is also entering the trigger.

  • Add some debugging lines to see what’s actually happening:

         function OnTriggerEnter(otherObj: Collider) {
             Debug.Log(otherObj.name + " entered trigger");
             if (otherObj.tag == "Graphics") {
                 Debug.Log("Tag is Graphics; playing audio");
                 audio.Play();
             }
         }
    
  • If you get " entered trigger" you know that the trigger happened.

  • If you do not get “Tag is Graphics; playing audio”, then whatever entered the trigger doesn’t match your condition for playing audio.

  • If you do get “Tag is Graphics; playing audio” but no audio plays, then there’s something wrong with the AudioSource component on soundtrigger1 (or your speakers are turned off) :slight_smile: