Programming Sounds on Collision

Hi everyone. I was just wondering how to program the sound for a bullet or a missile hitting a wall. I have the .wav file for the sound effect. I’m just not sure how to code it.

Thank you very much for your time!

If the object uses Rigidbody physics then implement OnCollisionEnter (check out tutorials).

If not then you need a way to decide you hit something. If the something has a collider, you can use Raycast to decide that.

If you don’t have a collider on things, you would have to check things by math, such as by rectangles or sphere distance, but that’s silly, since Unity can do the above two things so easily.

2 Likes

For this kind of thing I generally don’t use any code for the sound specifically. When a projectile hits something, I usually will instantiate some kind of impact prefab. Usually it will have particle systems to show flying debris or an explosion, maybe a point light flashes, and an audio source for the sound effect.

So the code is mostly just to detect the collision, instantiate the impact prefab, and destroy the projectile gameobject (it also might talk to a camera shake script attached to the camera). The impact prefab will just have a simple script which will destroy itself after a couple seconds, and maybe control the point light so it flashes for just 1 or 2 frames. But the audio source and particle systems are just set to play on awake.

If you do want to control an audio source via code though, you can just call Play or PlayOneShot.

2 Likes

Thank you very much for the quick responses! I believe my question has been answered and I appreciate your time :slight_smile:

1 Like