Beginning Unity 3D for iOS: Part 3/3
This is a post by Tutorial Team Member Christine Abernathy, an Engineer on the Developer Advocacy team at Facebook. You can also find her on Google+. Welcome to the third and final part the Beginning Unity 3D for iOS tutorial series! In the first part of this series, you toured the basic Unity tools, created […] By Christine Abernathy.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Beginning Unity 3D for iOS: Part 3/3
50 mins
- Getting Started: The End in Sight!
- Connect the Dots
- Create the Launcher
- Create the Obstacles
- Release the Krak… Err, Obstacles
- The Final Countdown
- Sometimes You Win, Sometimes You Lose
- Transformer-ing the Display Font
- It’s Always Play Time!
- Every Cube Deserves a Fresh Start
- This Message Won’t Self-Destruct
- Every Brave Cube Deserves a Soundtrack
- The Sounds of Victory and Defeat
- Thud in 3D
- A Little Cube Music
- Where To Go From Here?
The Sounds of Victory and Defeat
You're going to attach audio to the Goal GameObject that simulates a crowd cheering or jeering at the finish line.
Select the Goal GameObject in the Hierarchy View and add an audio source by selecting Component\Audio\Audio Source. Set the victory audio asset to the Inspector\Audio Source\Audio Clip property. De-select the Play on Awake option.
Now create a new JavaScript asset that will be used to play either a victory sound or a defeat sound. Name the new script FanReaction. Open the new script, remove the stub functions and add the following code:
var audioVictory : AudioClip;
var audioDefeat : AudioClip;
var volumeVictory : float = 2.0;
var volumeDefeat : float = 2.0;
function playSoundOfVictory(isVictory : boolean) {
// Stop any current audio
if (audio.isPlaying)
audio.Stop();
// Play either the sound of victory or defeat.
audio.clip = isVictory ? audioVictory : audioDefeat;
audio.volume = isVictory ? volumeVictory : volumeDefeat;
audio.Play();
}
function resetGame() {
// Reset to original state, stop any audio
if (audio.isPlaying)
audio.Stop();
}
@script RequireComponent(AudioSource)
The script takes in two audio clips, one for victory and one for defeat. The playSoundOfVictory() function first stops any audio that's currently playing, then plays the required audio based on the isVictory input.
The resetGame() function stops any audio that's playing. You'll shortly wire up the GameController to call resetGame() every time the game is restarted.
Attach this new script to the Goal GameObject. Set the victory audio asset to the Audio Victory variable. Set the defeat audio asset to the Audio Defeat variable.
Edit the GameController script and make the following changes:
var fanReactionScript : FanReaction;
...
function Update() {
if (!gameRunning)
return;
// Keep track of time and display a countdown
gameTimeRemaining -= Time.deltaTime;
if (gameTimeRemaining <= 0) {
timedOut = true;
gameRunning = false;
// Play the sound of defeat
fanReactionScript.playSoundOfVictory(false);
}
}
...
function MissionComplete() {
if (!gameRunning)
return;
missionCompleted = true;
gameRunning = false;
// Play the sound of victory
fanReactionScript.playSoundOfVictory(true);
missionCompleteTime = gameTimeAllowed - gameTimeRemaining;
}
The code defines a new public variable that references the FanReaction script. You modify MissionComplete() to call playSoundOfVictory(), passing in true to play the victory sound. You also modify Update() to call playSoundOfVictory(), passing in false to play the defeat sound.
You can now link the FanReaction script in the Goal GameObject with the variable in the Main Camera's GameController script component. Select Main Camera and then click on the circular icon next to the fanReactionScript variable under the GameController component in the Inspector. In the dialog that pops up, select the Goal GameObject, then close the pop-up.
To call resetGame() in FanReaction, select the Main Camera Object. In the Game Controller component section in the Inspector, increase the Game Objects To Reset array size from 2 to 3. Set the Goal GameObject to Element 2.
Preview the game and test out the victory and defeat scenarios to make sure the game plays the correct sounds. Verify that the sounds are stopped when you hit Play Again.
Thud in 3D
It would also be nice to have some sort of a sound when obstacles hit the ground. To achieve this, you'll attach an audio source to the Obstacle Prefab, then detect collisions so you can play the impact audio when the obstacles fall or bump into anything.
Add an Audio Source component to the Obstacle Prefab. Assign the impact audio to the Audio Clip property.
Create a new JavaScript asset and rename it to ObjectCollision. Edit the script, delete the stubbed functions and add the following code:
var impact : AudioClip;
function OnCollisionEnter () {
audio.PlayOneShot(impact);
}
@script RequireComponent(AudioSource)
The code implements the predefined OnCollisionEnter() event function and calls the audio.PlayOneShot() function to play the impact audio clip. audio.PlayOneShot() illustrates another way to play audio, allowing you to pass in the audio you wish to play.
Attach the script to the Obstacle Prefab. Set the impact audio asset to the Impact variable in the script.
Preview the game and verify that you hear a pleasing thud sound when obstacles hit the ground or another object. Note that closer the obstacles are to the player, the louder the sounds.
A Little Cube Music
Your game's almost complete. But there's one thing missing – some background tunes.
Music does a lot to set the mood for a game. It can get a user’s adrenaline flowing and help them “feel” the game environment by providing contextual clues like bird sounds or wolves howling. So add some music!
Add an Audio Source component to the Main Camera GameObject. Set the background audio asset to the Audio Clip property.
Select the Play on Awake and the Loop options. These ensure that the background music starts as soon as the game starts and that it will play continuously.
Adjust the volume property to 0.1 so it doesn’t drown out the other sounds. If you're using your own sounds, tweak the volume level depending on your music's default volume level to achieve the same goal. Users should be able to hear all the sound effects while the background music is playing.
Preview the project in the Unity Editor. When completely satisfied, deploy the project to your iOS device. You'll need to add the Level_3 scene in the Build Settings.
Test out the gameplay on your iOs device while you enjoy the sounds you've added.
Your Heroic Cube has a soundtrack to glorify its bravery!
Where To Go From Here?
Congratulations, you've made it to the end of this whirlwind walkthrough of the basics of Unity! You’ve shown as much verve and vigor as your Heroic Little Cube. This could be the beginning of a wonderful journey with Unity gaming.
Here are the source files with all of the code from this tutorial series: Unity Project, Xcode Project.
Believe it or not, you've just scratched the surface – there's a whole lot more to learn. Stay tuned for an upcoming intermediate tutorial series that will take you to the next level with Unity!
In the meantime, be sure to stop by the forums with your questions and feedback, and have fun building awesome games!
This is a post by Tutorial Team Member Christine Abernathy, an Engineer on the Developer Advocacy team at Facebook. You can also find her on Google+.