Project 1: Space Shooter

How to play sound effects in Unity

Play vs PlayClipAtPoint

Eero Saarinen

--

Background music is a nice way to enhance the game experience, but it’s still not enough. To really make the game immersive, it has to have sound effects. In my game’s case there are at least three possibilities for it. Namely picking a powerup, laser shot and the most satisfying one, the explosion.

So how to play these at the correct moment? Let’s start with the easiest one, laser shot. My laser’s firing mechanism is in the Player script, so it stands to reason that this is where I should play it. First I have to add an AudioSource component for my player, like I did last time.

Getting the reference for the AudioSource component.

Then, to be able to play laser being shot at the right moment, I have to get a reference to the AudioSource, which I will implement in the Start method. Nothing new here, just remember to make a null check. After that, all I have to do is to use method Play once the player has fired the laser.

For the enemies’ explosion the method is exactly the same, that is play it once the enemy explodes. But the asteroid and the player uses the explosion prefab, so I can attach the sound to the prefab and enable the Play On Wake, to make it play once the prefab has been instantiated.

For the explosion prefab no coding was necessary.

The real difference comes with the powerups. Because they wink out of existence once collected, I can’t use the Play method here. Or I can, but because the powerup object is destroyed without a delay, the sound clip will never be heard.

In these sorts of situations Unity provides an alternative way of playing sounds. A method called PlayClipAtPoint, this will produce an audio source, play the clip at the specified point and dispose of the audio source once the clip has been played. This way I don’t have to deactivate the powerup to hide it and introduce a delay to the Destroy method, just to be able to play the clip.

There is one caveat on using the PlayClipAtPoint method, and that is the volume. Depending on where the sound is being played, it will either be muted or close to the same level as the rest of the sounds. While it would be nice to have the clip played at the position where it was picked, I decided to use a fixed z-location for the powerup clip, so that it will actually be heard.

Playing the power up’s pickup sound.

The z-location is the same as the main cameras, that is -10. Otherwise the location of the powerup is used, this will create a subtle positional audio effect.

--

--