17: More sounds
Let’s add a sound for when our asteroids blow up.
You’ll have noticed that we didn’t need any code for our LaserBlast sounds, and that might have surprised you. That’s because we got lucky, and we didn’t need to. In general, you will, and we’ll look at that now. If you look at the setup for our LaserBlast, you’ll see in the AudioSource that there is an option checked called “Play On Awake”. This says that whenver our object “wakes up”, the sound should play and since the Rigidbody component sets our LaserBlast to “Start Awake” it goes off as soon as our laser blast is constructed, which is exactly what we wanted. Job done, free of charge.
If we did the same though, with our asteroids, there would be three copies of the noise when our asteroids were hit, as the new smaller ones were created, or none, when the smallest are destroyed. So we need to do something different.
In the Asteroid script, we’ll add a variable which links to the sound clip we want to play, and then we’ll trigger it in code when we blow up an asteroid.
Refresh your assets in Unity, and drag a suitable audio clip onto the reference field in the asteroid script for each of your asteroid prefabs. Here is one you can try:
The number in the sound function is the volume, a number between 0 and 1. You can tune these so they are balanced (the laser blast in the previous step is WAAAY louder than the explosion above). For the laser blast, go to the inspector and adjust the volume there.
You may have noticed that the laser blast sound can be cut short sometimes. This is because in these cases the laser blast is destroyed before the sound finishes playing. If this bothers you, remove the audio source and copy the process we used here for the asteroids.
What is happening with our asteroid explosions is that when we want to play the sound an AudioSource is created at the location of the asteroid, but it is not attached to the asteroid. So when the asteroid is destroyed the AudioSource is still there. The sound plays, and the AudioSource destroys itself automatically when the sound is finished.
|
|