Another thing that we can do to give the project a little more polish is add in sound effects and background music. Let's do that now. Perform the following steps:
EnemyBehaviour
script! As usual, we'll need to add in a new variable for us to use to play whenever we're hit:// What sound to play when hit public AudioClip hitSound;
CollisionEnter2D
function. After the Destroy(theCollision.gameObject)
line, add the following code:// Plays a sound from this object's AudioSource GetComponent<AudioSource>().PlayOneShot(hitSound);
In this instance, I used the GetComponent
function to access the AudioSource
component that is attached to the game object this is attached to. It is important to note that GetComponent
is a fairly expensive function to call. Since this will only be used once, it's OK to use like this; but if you were to use this more than once, I would suggest creating an AudioSource
variable and setting it in the Start
function instead like we will be doing in the next section.
For more information about the
PlayOneShot
function, check out http://docs.unity3d.com/ScriptReference/AudioSource.PlayOneShot.html.
For more information on the Audio Source component (audio), check out http://docs.unity3d.com/ScriptReference/AudioSource.html.
Example Code
folder, so open your project folder via your Explorer and move the folder into your project's Assets
and then return to Unity.Hit Sound
variable in the EnemyBehaviour
script to the hit sound that we've imported by using drag and drop. Now, if we play the game, when we hit an enemy, the sound will be played! Now, let's have a sound if we destroy the enemy!explode
sound.Now, if you play the game, hitting the object will play one sound, and when the object is destroyed, the explosion will play a sound. Because the sound is in the Audio Clip property, we can just check Play On Awake or call the Play
function. However, if you want an object to play multiple sounds, it's better to have separate AudioClip
variables just as we did with EnemyBehaviour
.
playerShip
and add an audio source. PlayerBehaviour
, and add in two new variables, as follows:// What sound to play when we're shooting public AudioClip shootSound; // Reference to our AudioSource component private AudioSource audioSource;
Start
function with the following:void Start() { audioSource = GetComponent<AudioSource>(); }
ShootLasers
function:audioSource.PlayOneShot(shootSound);
PlayerBehaviour
component to the shoot
sound effect..25
.The background music is provided for this project by Stratkat (Kyle Smith). If you are interested in more of his work, check out his website at http://daydreamanatomy.bandcamp.com/.
Although we won't see any changes at this point for those of you actually running the game, you'll notice quite a change when the game is started. It's already feeling much more like a game.