- Home /
Audio, play when laser hits object
I have an audio source and a sound attached to a laser prefab which acts like a bullet. I want an audio clip to be played when the laser hits an object with the tag "Block". Here is my script:
var mySound : AudioClip;
function Start () {
}
function Update () {
//move laser forward
transform.position += transform.forward * laserSpeed * Time.deltaTime;
DestroyObject();
}
//destroy object after 5 seconds
function DestroyObject(){
yield WaitForSeconds (5);
Destroy (gameObject);
}
function OnTriggerEnter (other : Collider) {
if(other.tag == "Block"){
audio.PlayOneShot(mySound);
Destroy(other.gameObject);
}
Destroy(gameObject);
}
If I have the "audio.PlayOneShot(mySound);" in the update function the sound fires, so I must have everything setup correctly in the inspector, I cannot figure out why it will not fire from here.
Answer by DESTRUKTORR · Aug 25, 2013 at 06:50 PM
It's not registering the collision. Make sure the game object this is attached to has a proper collider (I'd suggest a box collider, as they're computationally the cheapest collider Unity has, as far as I know, and will react to virtually any type of collision), and ensure that said collider has "isTrigger" set to true (should be checked, in the inspector).
Also, ensure that the object it is colliding with has a compatible collider, as well.
See the table at the bottom of this page to find out specifically what "OnTriggerEnter" requires, with a box collider, to be called.
A box collider is already attached and it is set at isTrigger. Also other statements work in the collision function such as Destroy(other.gameObject).