Adding sounds

When you start adding sounds in to your game, it takes on a whole new dimension, you'd be surprised how a game that seems unfinished can suddenly feel almost complete just by adding some sounds effects. We're going to add a sound that will play every time a crate is moved on to a goal tile. With keeping our project tidy in mind, the first step is to create a folder that will store all our sound files.

Click on the Create dropdown menu in the Project panel. Click on Folder and a new folder will be created in the project panel, call the folder Sounds. Import the asset crateOnGoal.mp3 from the files for this chapter to your new Sounds folder.

Sound in Unity requires the following three things:

  • A sound to play
  • A source for the sound to come from
  • A listener to hear the sound

Our Main Camera already has an Audio Listener component attached to it and we have already imported our sound to play, all that's left is to add an audio source with a reference to our sound and a trigger to call it. Click on the Sokoban GameObject, then click on Component | Audio | Audio Source. You'll see in the Inspector panel that the new component has appeared that is Audio Source.

Drag your crateOnGoal sound effect to the Audio Clip section of the component; this is how Audio Source knows which sound to play. We also need to uncheck the Play On Awake box, as we only want the sound to play when a box is moved on to a goal by the player, as shown in the following screenshot:

Adding sounds

Our audio component is now configured. Go back to MonoDevelop and edit your Sokoban script, we need to find the appropriate place to add our sound code. The MovePlayer method is a good place. We need to add it when we know a move has finished, so it will be inside of the if (movingSteps == 10) { statement. As we want it to play only when moving a crate we'll also have to have it inside the if (movingCrate != "") { statement. Add the following code at the bottom of the statement, inside the closing brace:

if (levels[currentLevel][pRow + 2 * tRow][pCol + 2 * tCol] == 5) {
  audio.Play();
}

We only want to play the sound if the crate is on a goal tile, so we check that the array's index is 5, which is the number we use for a crate on a goal tile. As Audio Source is attached to the same GameObject as the Sokoban script, we can just call audio.Play to play the sound. Click on the play icon at the top-middle of the Unity screen and position a crate on a goal tile, you should have a cool space-style sound effect play. If not then check you dragged the sound file to the Audio Source component and that your sound on your test device is turned up.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.10.32