Lesson 8
Add sounds
Play a sound when you jump and when you grab a coin, and add music.
Draft lesson: nobody has followed it from start to finish in the editor yet, so a step may not match what you see.
Video coming soon
We are making a video for this lesson. For now, follow the steps below!
In this lesson you will
- Add sound files to your project
- Play a sound from code
- Add music that loops
1. Add your sounds
Drag sound files (MP3, OGG or WAV) from your computer onto the Assets panel. Name them jump,
coin and music.
2. A jump sound
- Click
Player, then Add Component, and add an Audio Source. - Choose the
jumpsound, and name the Audio SourceJump.
In your Player script, add one line where the player jumps:
if (Input.IsKeyPressed(KeyCode.Space) && this.body.isGrounded) {
this.body.ApplyLinearImpulse(0, -4);
this.mGameObject.GetAudioSource('Jump')?.Play();
}
3. A coin sound
The coin disappears, and its sounds stop with it! So the coin asks the game to play the sound.
In your Coin script, add this line before GameObject.Destroy(...):
Sound.PlayOneShot('coin');
4. Music
- Make an Empty GameObject called
Music. - Add an Audio Source with the
musicsound. - Turn on Play on start and Loop.
Press Play. Now your game has music!
Try this
- Make the music quieter with Volume.
- Change the jump sound's Pitch. Funny!
Try it here
Your mission
Turn Loop on and off, and press Play to hear the difference.
Soon, a small piece of the editor will be right here, so you can practise without leaving the lesson. For now, try it in the editor!