My 90 day journey becoming a Unity game developer: Day-37

Objective: Adding sound effects when we capture powerups.

Now the first instinct is to add AudioSource’s to each powerup and add the audio clip representing the powerup sound effect to be used. However, we will run into a problem in that the audio clip will not be heard when the player grabs the powerup. This will happen because the Destroy game object function will happen before the audio clip can actually play.

Therefore, what we will do instead is go to the Powerup script, and create a variable that will assign the particular audio clip to each powerup using the SerializeField attribute. Then in the OnTriggerEnter2D() function, we will insert the audio clip to be played using the PlayClipAtPoint() function because it will create an audio source and dispose of it once the clip has finished playing at a given position in world space. We can also control the volume level in this function as well by adding the third parameter as a Float .

Playing the powerup sound effect using PlayClipAtPoint() function.

Finally, we will select the 3 powerup prefabs, and add the powerup sound effect in the Power Up Clip variable slot under the Power Up script component.

Assigning the powerup sound effect through the variable slot in the PowerUp script component.
Sound effect will play when we grab each powerup.

Next time we will work on building the game.

Learning to become a Unity game developer.