Terry Norton Learning C# by Developing Games with Unity 3D Beginner#039s Guide (2013)


Чтобы посмотреть этот PDF файл с форматированием и разметкой, скачайте его и откройте на своем компьютере.
with Unity 3D Beginner's Guide
Learn the fundamentals of C# to create scripts for your
Terry Norton
BIRMINGHAM - MUMBAI
with Unity 3D Beginner's Guide
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmi�ed in any form or by any means, without the prior wri�en permission of the
publisher, except in the case of brief quota�ons embedded in cri�cal ar�cles or reviews.
Every e�ort has been made in the prepara�on of this book to ensure the accuracy of the
informa�on presented. However, the informa�on contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark informa�on about all of the
companies and products men�oned in this book by the appropriate use of capitals. However,
Packt Publishing cannot guarantee the accuracy of this informa�on.
First published: September 2013
Produc�on Reference: 1190913
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK..
Cover Image by Ar�e Ng (
Terry Norton
Reviewers
Gaurav Garg
Kris�an Hedeholm
Acquisi�on Editor
Lead Technical Editor
Dayan Hyames
Technical Editors
Ruchita Bhansali
Dylan Fernandes
Dipika Gaonkar
Monica John
Proshonjit Mitra
Project Coordinator
Apeksha Chitnis
Proofreader
Ameesha Green
Indexers
Rekha Nair
Tejal Soni
Graphics
Ronak Dhruv
Produc�on Coordinator
Cover Work
Terry Norton
was born and raised in California. During the Vietnam era, he served six
and half years in the US Air Force. While in the military, he was trained in electronics for
electronic counter-measures. Upon discharge, he earned his Electrical Engineering degree,
and later working for Joslyn Defense Systems in Vermont, designing and developing test
equipment for the US Navy.
When personal computers came on the scene, he took an interest in building computers, but
never quite delved deep into the programming side. It wasn't un�l 2004 that programming
peaked his interest. He began wri�ng ar�cles for OS/2 Magazine to teach C++ programming.
Unfortunately, damaging his le� hand in a snowblower accident in 2005 ended his wri�ng for
a couple years.
IBM abandoned OS/2, so Terry bought his �rst Apple computer in early 2006. He tried a
few �mes to learn Objec�ve-C, but work and family always seemed to sidetrack his e�orts.
It wasn't un�l about 2010 when he discovered Unity and the need to write scripts, that he
�nally made some progress into the programming world. He began wri�ng an online
tutorial for UnityScript �tled
UnityScript for Noobs
. It was a basic tutorial for beginners
made available just before Unite 2011.
Since then, Terry has been learning C# for wri�ng scripts for Unity. Packt Publishing no�ced
UnityScript for Noobs
and asked if he would be interested in wri�ng a book about learning
UnityScript. He declined. He felt that C# was a be�er language, and his heart just wasn't into
UnityScript any longer. Two weeks later, Packt o�ered him the opportunity to write a book
about learning C# for Unity. He jumped on it.
I want to thank my daughter Emily Norton, the ar�st in the family, for
helping me with the graphic's design.
Gaurav Garg
was born in Delhi. He is a Computer Applica�ons graduate from Indira
Gandhi University and has passed his higher secondary from the CBSE Board. During his
under- graduate studies, he started his career as an indie game programmer, but didn't
gain success because of a lack of or say, no experience. A�er this, he learnt that passion is
not the only thing for ge�ng success; experience ma�ers a lot. Then he joined Isis Design
Service as a game programmer, where he published a few iOS �tles and one web-based
game. He worked there for a year and a half. Then, he moved to Jump Games, Pune, and
worked on a few good game �tles such as Realsteal and Dancing with the Stars. Now, he
works for Mr Manvender Shukul in Lakshya Digital Pvt ltd. and has been there since the
past year.
He hasn't reviewed a book before, but one of his ar�cles was published in Game Coder
Magazine. The ar�cle was on Unity3D. You can download the ar�cle from his personal
website,
I would like to thanks my parents who taught me the value of hard work
and an educa�on.
I need to thanks my friends, par�cularly Manjith and Vibhash, who always
took the �me to listen, even when I was just complaining. They always are
my best supporters and advisors.
Finally, I would like to thank Harshit who gives me this opportunity.
Kris�an Hedeholm
studied Computer Science at Aarhus University and now works as a
game programmer at Serious Games Interac�ve in Copenhagen, Denmark. Since Kris�an
joined the game industry back in 2009, he has worked on a couple of released casual games.
In addi�on to this, he is also the chairman of an associa�on called Young Game Developers,
which aims to spread informa�on about game development among children and teenagers.
In the future, Kris�an will use his "computer mind" to develop ar��cial intelligence and
dynamic di�culty adjustment systems for computer games.
When Kris�an isn't developing games, teaching others to develop games, or playing games
himself, he thinks about them a lot!
SupporP �les, eBooks, discounP offers Mnd more
You might want to visit
for support �les and downloads related to
your book.
Did you know that Packt o�ers eBook versions of every book published, with PDF and ePub
�les available? You can upgrade to the eBook version at
and as a print
book customer, you are en�tled to a discount on the eBook copy. Get in touch with us at
for more details.
At
, you can also read a collec�on of free technical ar�cles, sign up
for a range of free newsle�ers and receive exclusive discounts and o�ers on Packt books
and eBooks.
Do you need instant solu�ons to your IT ques�ons? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's en�re library of books.
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
If you have an account with Packt at
, you can use this to access
PacktLib today and view nine en�rely free books. Simply use your login creden�als for
immediate access.
TMNle of FonPenPs
Preface
Chapter 1: Discovering Your Hidden Scrip�ng Skills
Prerequisite knowledge for using this book
Dealing with scriptphobia
Teaching behaviors to GameObjects
Choosing to use C# instead of UnityScript
Reason 1 for choosing C# – vast amount of documenta�on on the Internet
Reason 2 for choosing C# – �exibility to use Unity scripts and regular
C# code �les
Reason 3 for choosing C# – coding rules are speci�c
Maneuvering around Unity's documenta�on
Time for ac�on – opening the Reference Manual documenta�on
for the transform Component
Time for ac�on – opening the scrip�ng reference documenta�on
for the transform component
Are we really supposed to know all that stu�?
What is all that informa�on?
Working with C# script �les
Time for ac�on – create a C# script �le
Introducing the MonoDevelop code editor
Syncing C# �les between MonoDevelop and Unity
Time for ac�on – opening LearningScript in MonoDevelop
Watching for a possible "gotcha" when crea�ng script �les in Unity
Fixing sync if it isn't working properly
Summary
Chapter 2: Introducing the Building Blocks for Unity Scripts
Using the term method instead of func�on
Understanding what a variable does in a script
Naming a variable
A variable name is just a subs�tute for a value
Time for ac�on – crea�ng a variable and seeing how it works
Time for ac�on – changing the number 9 to a di�erent number
Using a method in a script
What is a method?
Time for ac�on – learning how a method works
What's in this script �le?
Method names are subs�tutes too
Introducing the class
By using a li�le Unity magic, a script becomes a Component
A more technical look at the magic
Even more Unity magic
Components communica�ng using the Dot Syntax
What's with the dots?
Summary
Chapter 3: Ge�ng into the Details of Variables
Wri�ng C# statements properly
Understanding Component proper�es in Unity's Inspector
Variables become Component proper�es
Unity changes script and variable names slightly
Changing a property's value in the Inspector panel
Displaying public variables in the Inspector panel
Time for ac�on – making a variable private
Naming your variables properly
Begin variable names with lowercase
Using mul�-word variable names
Declaring a variable and its type
The most common built-in variable types
Time for ac�on – assigning values while declaring the variable
Where you declare a variable is important
Variable scope – determining where a variable can be used
Summary
Chapter 4: Ge�ng into the Details of Methods
Ending a method de�ni�on using curly braces
Using methods in a script
Naming methods properly
Begin method names with an uppercase le�er
Using mul�-word names for a method
Parentheses are part of the method name
De�ning a method properly
The minimum requirements for de�ning a method
Understanding parentheses – why are they there?
Time for ac�on – adding code between the parentheses
Specifying a method's parameters
How many parameters can a method have?
Calling a method
Using arguments in the parentheses of a method
Returning a value from a method
Time for ac�on – returning a value from AddTwoNumbers()
Calling a method is a logic detour
Using Unity's Update and Start methods
The Start method is called one �me
The Update method is called over and over and over…
Summary
Chapter 5: Making Decisions in Code
Tes�ng condi�ons with an if statement
Tes�ng if condi�ons are true or false
Time for ac�on – create a couple of if statements
Using the NOT operator to change the condi�on
Checking many condi�ons in an if statement
Time for ac�on – create if statements with more than one condi�on to check
Using an if-else statement to execute alternate code
Time for ac�on – add "else" to the if statement
Storing data in an array, a List, or a Dic�onary
Storing items in an array
Storing items in a List
Time for ac�on – create a List of pony names
Storing items in a Dic�onary
Time for ac�on – create a dic�onary of pony names and keys
Using a Collec�on Ini�alizer to add items to a List or Dic�onary
Time for ac�on – adding ponies using a Collec�on Ini�alizer
Looping though lists to make decisions
Using the foreach loop
Time for ac�on – using foreach loops to retrieve data
Using the for loop
Time for ac�on – selec�ng a pony from a List using a for loop
Time for ac�on – �nding data and breakout of the while loop
Summary
Chapter 6: Using Dot Syntax for Object Communica�on
Using Dot Syntax is like addressing a le�er
Simplifying the dots in Dot Syntax
Using access modi�ers for variables and methods
Working with objects is a class act
Using Dot Syntax in a script
Accessing a Component's own variables and methods
Time for ac�on – accessing a variable in the current Component
Accessing another Component on the current GameObject
Time for ac�on – communica�ng with another Component on the Main Camera
Accessing other GameObjects and their Components
Time for ac�on – crea�ng two GameObjects and a new script
Accessing GameObjects using drag-and-drop versus wri�ng code
Time for ac�on – trying drag-and-drop to assign a GameObject
Summary
Chapter 7: Crea�ng the Gameplay is Just a Part of the Game
Applying your new coding skills to a State Machine
Understanding the concepts of a State Machine
Bene�ts of by using a State Machine
Following the State Machine logic �ow
Delega�ng game control to a State
Switching to another State when called to do so
Keeping track of the ac�ve State
Crea�ng Components objects and C# objects
Unity creates Components behind the scenes
Instan�ate a class to create an object
Time for ac�on – crea�ng a script and a class
Time for ac�on – instan�a�ng the BeginState class
Specifying a �le's loca�on with a namespace declara�on
Loca�ng code �les with a using statement
Introducing the C# interface
The State Machine and the interface guarantee
Time for ac�on – implemen�ng an interface
Summary
Chapter 8: Developing the State Machine
Crea�ng four State classes
Time for ac�on – modyi�ng BeginState and add three more States
Se�ng up the StateManager controller
Studying an example of inheritance
Enter the IStateBase interface again
Time for ac�on – modify StateManager
Adding another State
Time for ac�on – modifying PlayState to add another State
Adding OnGUI to the StateManager class
Time for ac�on – adding OnGUI() to StateManager
Changing the ac�ve State and controlling the Scene
Time for ac�on – adding GameObjects and a bu�on to the Scene
Pausing the game Scene
Time for ac�on – adding code to pause the game Scene
Time for ac�on – crea�ng a �mer in BeginState
Time for ac�on – se�ng up another Scene
Changing Scenes destroys the exis�ng GameObjects
Keeping GameManager between scenes
Time for ac�on – adding the Awake method to StateManager
Time for ac�on – adding the code to change the Scenes
Verifying the code of your classes
Summary
Chapter 9: Start Building a Game and Get the Basic Structure Running
Easing into Unity's scrip�ng documenta�on
Reading the Unity Reference Manual �rst
Finding code examples in the Scrip�ng Reference as needed
Setup the State Machine and add a Player GameObject
Time for ac�on – se�ng up nine States and three Scenes
Calling the Restart method of the StateManager
Add a Player GameObject
Placing and using the Player Collider
Placing and using the Sphere Collider
Time for ac�on - adding a Player GameObject
Storing game data in its own script
Time for ac�on – crea�ng a GameData script
Displaying the splash screens
Controlling the Player GameObject
Time for ac�on – rota�ng Player in SetupState
Adding the Player Color op�on
Time for ac�on – changing the color using GUI bu�ons
Adding the Lives op�on for Player
Time for ac�on – se�ng the Lives for Player
Summary
Chapter 10: Moving Around, Collisions, and Keeping Score
Visualizing the completed game
Switching to the �rst play State and playable scene
Loading Scene1 using code
Adding cameras for di�erent viewing op�ons
Time for ac�on – se�ng up two addi�onal cameras in the scene
A�aching scripts to the new cameras
Time for ac�oning – a�ach the LookAtPlayer camera script
Time for ac�on – a�aching the FollowingPlayer camera script
Moving the Player using Rigidbody physics
Time for ac�on – adding a Rigidbody to the Player
Keeping score during the game
Ini�alizing the scoring system
Keeping score in the Scene1 play State
Losing the game in Scene1
Winning the level in Scene1
Determining how to win or lose
Time for ac�on – crea�ng a good and bad prefab
Scoring for the win
Losing when Player crashes
Shoo�ng projec�les at the orbs
Time for ac�on – crea�ng the EnergyPulse prefab
Shoo�ng a single-shot EnergyPulse
Shoo�ng rapid-�re EnergyPulses
The EnergyPulse is �red
Controlling EnergyPulse objects
Summary
Chapter 11: Summarizing Your New Coding Skills
Coding a Unity Project
Working with objects
Scratching the surface of C# programming
Looking at even more C# features
Looking at even more Unity features
Controlling the game with a State Machine
Using a State Machine is a design pa�ern choice
Using the State Machine at the GameObject level
Pulling all the li�le C# pieces together
Learning more a�er this book
Visit my favorite website for C#
Visit my favorite websites for Unity coding:
Summary
Appendix A: Ini�al State Machine �les
BeginState
SetupState
PlayStateScene1_1: (1 of 2 available States in Scene1)
PlayStateScene1_2: (2 of 2 available States in Scene1)
WonStateScene1
LostStateScene1
PlayStateScene2
WonStateScene2
LostStateScene2
StateManager
IStateBase
Appendix B: Completed code �les for Chapters 9 and 10
BeginState
SetupState
PlayStateScene1_1: (1 of 2 available States in Scene1)
PlayStateScene1_2: (2 of 2 available States in Scene1)
WonStateScene1
LostStateScene1
PlayStateScene2
WonStateScene2
LostStateScene2
StateManager
PlayerControl
GameData
LookAtPlayer
FollowingPlayer
EnergyPulsePower
IStateBase
Appendix C: Pop vuiz Answers
Index
Unity has become one of the most popular game engines for developers, from the amateur
hobbyist to the professional working in a large studio. Unity used to be considered a 3D tool,
but with the release of Unity 4.3, it now has dedicated 2D tools. This will expand Unity's use
even more.
Developers love its object-oriented drag-and-drop user interface which makes crea�ng a
game or interac�ve product so easy. Despite the visual ease of working in Unity, there is a
need to understand some basic programming to be able to write scripts for GameObjects.
For game developers that have any programming knowledge, learning how to write scripts
is quite easy. For the the ar�st coming to Unity, crea�ng the visual aspects of a game is a
breeze, but wri�ng scripts may appear to be a giant roadblock.
This book is for those with no concept of programming. I introduce the building blocks, that
is, basic concepts of programming using everyday examples you are familiar with. Also, my
approach to teaching is not what you will �nd in the typical programming book. In the end,
you will learn the basics of C#, but I will spoon-feed you the details as they are needed.
I will take you through the steps needed to create a simple game, with the focus not being
the game itself but on how the many separate sec�ons of code come together to make a
working game. I will also introduce the concept of a State Machine to organize code into
simple, game controlling blocks. At the end, you will be saying "Wow! I can't believe how
easy that was!"
Chapter
Discovering Your Hidden Scrip�ng Skills,
explains that the very �rst thing you
need to do is overcome your perceived fear of wri�ng scripts. You'll see that wri�ng scripts
is very similar to many of your daily rou�nes. We also have a �rst look at Unity's scrip�ng
documenta�on. Finally, we see how to create a C# script �le in Unity.
2 ]Chapter
Introducing the Building Blocks for Unity Scripts,
explains that there are two
primary building blocks for wri�ng code, variables and methods. This chapter introduces
the concepts of a variable and a method. With these two building blocks, we look into the
concept of a "class," a container of variables and methods used to create Unity Components.
Finally, communica�on between GameObjects is discussed by introducing Dot Syntax.
Chapter
Ge�ng into the Details of Variables,
explains using variables in detail. We see how
they're used for storing data, and how the magic works to turn variables into Component
proper�es which appear in the Unity Inspector panel.
Chapter
,
Ge�ng into the Details of Methods,
explains how methods perform the ac�ons that
take place on GameObjects. We see how to create and use methods in detail. We also look into
two of Unity's most o�en used methods, the Start() method and the Update() method.
Chapter
explains that during gameplay, decisions have to be
made about many things, just like you do in your daily life. We look at many of the ways
choices are made and some of the common reasons for which decisions are required.
Chapter
Using Dot Syntax for Object Communica�on,
shows us what Dot Syntax actually is,
a simple address format to retrieve informa�on or send informa�on to other Components.
Chapter
Crea�ng the Gameplay is Just a Part of the Game,
shows that developing the
gameplay is fun, but there are other parts needed to make a fully func�onal game. We look
into some of the possible parts needed and how to organize all the parts by introducing the
use of a State Machine.
Chapter
Developing the State Machine,
creates a simple State Machine to show how it
works, and see the simplicity it brings for controlling a game. We show how to change Scenes
for a mul�-level game and how to deal with GameObjects when changing to another scene.
Chapter
Start Building a Game and Get the Basic Structure Running,
teaches us how to
access and use Unity's Scrip�ng Reference and the Reference Manual for the features we
want. Then we begin crea�ng a mul�-level game using the state machine and three scenes.
A Player GameObject is added and we learn how to control it.
Chapter
Moving Around, Collisions, and Keeping Score,
shows how to move the Player
around using Unity's physics system, and have cameras follow the Player's movements. We
develop a GUI scoring system, start shoo�ng projec�les at enemy objects, and see how to
win or lose the game. Ul�mately, we see how all the separate pieces of code come together
and work together.
Chapter
Summarizing Your New Coding Skills,
reviews the main points you learned about
programming with C# and working with objects. I tell you about some of the C# and Unity
features you may want to learn now that you understand the basics of C#. I will highlight
the bene�ts of incorpora�ng a state machine into your Unity projects. Finally, I present my
favorite sources for further learning.
Ini�al State machine �les
, shows the ini�al code for the classes needed
for changing States in our game. These State Machine classes are the star�ng point for
organizing and adding game code.
Completed code �les for Chapters 9 and 10
, shows all the class and script �les
used for playing our completed game.
You need the free version of Unity located at
The MonoDevelop code editor is included in the Unity installa�on.
Your computer will need to meet the minimum requirements for Unity as speci�ed at
Windows: XP SP2 or later; Mac OS X "Snow Leopard" 10.6 or later. Note that Unity was not
tested on server versions of Windows and OS X.
Graphics card with DirectX 9 level (shader model 2.0) capabili�es. Any card made since 2004
should work.
If you don't know anything about programming in general, wri�ng code, wri�ng scripts, or
have no idea where to even begin, then this book is perfect for you. If you want to make
games and need to learn how to write C# scripts or code, then this book is ideal for you.
In this book, you will �nd several headings appearing frequently.
To give clear instruc�ons of how to complete a procedure or task, we use:
Instruc�ons o�en need some extra explana�on so that they make sense, so they are
followed with:
What just happened?
This heading explains the working of tasks or instruc�ons that you have just completed.
You will also �nd some other learning aids in the book, including:
These are short mul�ple-choice ques�ons intended to help you test your own understanding.
These prac�cal challenges give you ideas for experimen�ng with what you have learned.
You will also �nd a number of styles of text that dis�nguish between di�erent kinds of
informa�on. Here are some examples of these styles, and an explana�on of their meaning.
Code words in text, database table names, folder names, �lenames, �le extensions,
pathnames, dummy URLs, user input, and Twi�er handles are shown as follows: "We
can include other contexts through the use of the include direc�ve."
A block of code is set as follows:
When we wish to draw your a�en�on to a par�cular part of a code block, the relevant lines
or items are set in bold:
Any command-line input or output is wri�en as follows:
Downloading the example code
You can download the example code �les for all Packt books you have purchased
from your account at h�p://www.packtpub.com. If you purchased this book
elsewhere, you can visit h�p://www.packtpub.com/support and register to have
the �les.e-mailed directly to you.
New terms
important words
are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "clicking the
Next
bu�on
moves you to the next screen".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or may have disliked. Reader feedback is important for us to
develop �tles that you really get the most out of.
To send us general feedback, simply send an e-mail to
and men�on the book �tle via the subject of your message.
If there is a topic that you have exper�se in and you are interested in either wri�ng or
contribu�ng to a book, see our author guide on
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.
You can download the example code �les for all Packt books you have purchased from your
account at
. If you purchased this book elsewhere, you can
and register to have the �les e-mailed directly
to you.
6 ]ErrataAlthough we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you �nd a mistake in one of our books—maybe a mistake in the text or the
code—we would be grateful if you would report this to us. By doing so, you can save other
readers from frustra�on and help us improve subsequent versions of this book. If you �nd
any errata, please report them by visi�ng
selec�ng your book, clicking on the
errata
form
link, and entering the details of
your errata. Once your errata are veri�ed, your submission will be accepted and the errata
will be uploaded on our website, or added to any list of exis�ng errata, under the Errata
sec�on of that �tle. Any exis�ng errata can be viewed by selec�ng your �tle from
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protec�on of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the loca�on
address or website name immediately so that we can pursue a remedy.
Please contact us at
with a link to the suspected
pirated material.
We appreciate your help in protec�ng our authors, and our ability to bring you
valuable content.
You can contact us at
if you are having a problem with any
aspect of the book, and we will do our best to address it.
Discovering Your Hidden
Computer programming is viewed by the average person as requiring long
periods of training to learn skills that are totally foreign, and darn near
impossible to understand. The word geek is often used to describe a person
that can write computer code. The perception is that learning to write code
takes great technical skill that is just so hard to learn. This perception is totally
unwarranted. You already have the skills needed but don't realize it. Together
we will crush this false perception you may have of yourself by refocusing, one
step at a time, the knowledge you already possess to write Unity scripts.
In this chapter we shall:
Deal with preconceived fears and concepts about scripts
See why we should use C# instead of UnityScript
Introduce Unity's documenta�on for scrip�ng
Learn how Unity and the MonoDevelop editor work together
Let's begin our journey by elimina�ng any anxiety about wri�ng scripts for Unity,
and become familiar with our scrip�ng environment.
8 ]PrerequisiPe knoRledge for using POis NookGreat news if you are a scrip�ng beginner! This book is for those with absolutely no
knowledge of programming. It is devoted to teaching the basics of C# with Unity.
However, some knowledge of Unity's opera�on is required. I will only be covering the parts
of the Unity interface that are related to wri�ng C# code. I am assuming that you know your
way around Unity's interface, how to work with GameObjects in your
, and how to
locate
Components
and view their
Proper�es
Inspector
You've got Unity up and running, studied the interface, added some GameObjects to the
Scene. Now
you're ready to have those GameObjects move around, listen, speak, pick up
other objects, shoot the bad guys, or anything else you can dream of. So you click on Play,
and nothing happens. Well darn it all anyway.
You just learned a big lesson, all those fantas�c, highly detailed GameObjects are dumber
than a hammer. They don't know anything, and they sure don't know how to do anything.
So you proceed to read the Unity forums, study some scrip�ng tutorials, maybe even copy
and paste some scripts to get some ac�on going when you press Play. That's great, but then
you realize you don't understand anything in the scripts you've copied. Sure, you probably
recognize the words, but you fail to understand what those words do or mean in a script. It
feels like gibberish.
You look at the code, your palms get sweaty, and you think to yourself, "Geez, I'll never be
able to write scripts!" Perhaps you have
scriptphobia
: the fear of not being able to write
instruc�ons (I made that up). Is that what you have?
The fear that you cannot write down instruc�ons in a coherent manner? You may believe
you have this a�ic�on, but you don't. You only think you do.
The basics of wri�ng code are quite simple. In fact, you do things every day that are just like
the steps executed in a script. For example, do you know how to interact with other people?
How to operate a computer? Do you fret so much about making a baloney sandwich that
you have to go to an online forum and ask how to do it?
Of course you don't. In fact, you know these things as "every day rou�nes", or maybe as
habits. Think for a moment, do you have to consciously think about these rou�nes you
do every day? Probably not. A�er you do them over and over, they become automa�c.
9 ]The point is, you do things everyday following sequences of steps. Who created these steps
you follow? More than likely you did, which means you've been scrip�ng your whole life.
You just never had to write down the steps, for your daily rou�nes, on a piece of paper
before doing them. You could write the steps down if you really wanted to, but it takes
too much �me and there's no need. But you do, in fact, know how to. Well, guess what?
To write scripts, you only have to make one small change, start wri�ng down the steps.
Not for yourself but for the world you're crea�ng in Unity.
So you see, you are already familiar with the concept of dealing with scripts. Most beginners
to Unity easily learn their way around the Unity interface, how to add assets, and work in
the Scene and Hierarchy windows. Their primary fear, and roadblock, is their false belief
that scrip�ng is too hard to learn.
Relax! You now have this book. I am going to get really basic in the beginning chapters.
Call them baby-steps if you want, but you will see that scrip�ng for Unity is similar to doing
things you
already do everyday. I'm sure you will have many "Ah-Ha" moments as you learn
and overcome your unjus��ed fears and beliefs.
Teaching behaviors to GameObjects
You have Unity because you want to make a game or something interac�ve. You've �lled your
game full of dumb GameObjects. What you have to do now is be their teacher. You have to
teach them everything they need to know to live in this make-believe world. This the part
where
you have to write down the instruc�ons so that your GameObjects can be smarter.
Here's a quote from the Unity Manual:
behavior
of GameObjects is controlled by the
Components
that are a�ached
to them... Unity allows you to create your own
Components
using scripts.
No�ce that word, behavior. It reminds me of a parent teaching a child proper behavior.
This is exactly what we are going to do when we write scripts for our GameObjects, we're
teaching them the behaviors we want them to have. The best part is, Unity has provided
a big list of all the behaviors we can give to our GameObjects. This list of behaviors is
documented in the Scrip�ng Reference.
This means we can pick and chose, from this list of behaviors anything we want a
GameObject to do. Unity has done all the hard work of programming all these behaviors
for you. All we need to do is use a li�le code to �e into these behaviors. Did you catch that?
Unity has already created the behaviors, all we have to do is supply a li�le bit of C# code to
apply these behaviors to our GameObjects. Now really, how di�cult can it be since Unity has
already done most of the programming?
10 ]FOoosing Po use F# insPeMd of UniPyScripP
So why
choose C# to create this code? This maybe a�er-the-fact informa�on for you if
you've already acquired this book and chosen to use C#, but these are valuable points
to know anyway:
C# is known as
a strictly-typed language. What does this means to you?
As you write code, Unity will catch coding errors immediately. Learning a subject
is always easier when the rules are speci�c, and not some fuzzy "you can if you
want to" kind of logic.
UnityScript is not a strictly-typed language. You have the poten�al to write code
that is not valid, but Unity won't catch the errors un�l you press Play.
Finding mistakes as you write the code is so much easier than having to deal
with them when a user has found them when they're playing the game.
Please be aware, it is easy to force UnityScript to be strictly-typed, but if you're
going to
do that, then you may as well be using C# anyway, which brings us back
to Reason 1.
Maneuvering around Unity's documentation
When we begin wri�ng scripts, we will be looking at Unity's documenta�on quite o�en,
so it's bene�cial to know how to access the informa�on we need. For an overview of a
topic we'll use the
Reference Manual
. For speci�c coding details and examples we'll use
Scrip�ng Reference
When you look at the code examples in the
Scrip�ng Reference
, they probably
won't make sense to you, which is expected at this point. In the beginning
chapters, as I teach you the basics of programming, it will be necessary for me
to use a few things in the
Scrip�ng Reference
such as displaying some output
to Unity's
. For now, just copy the code I use because you will be
learning the detail of it later.
To get a feel for
accessing Unity's documenta�on from within Unity, we'll use the
Camera
to demonstrate. Every GameObject in a Scene has a
Transform
Component, so
we'll look at the documenta�on for
Transform
Reference Manual
Scrip�ng
Reference
. Ge�ng to the informa�on is pre�y easy. Click on the �ny book icon with the
ques�on mark.
Hierarchy
tab, select the
Main Camera
Click on the book icon for the
Transform
What just happened?
The web
browser opened the
Reference Manual
showing informa�on about Transform.
From the
Reference Manual
, we'll now open the
Scrip�ng Reference
documenta�on for the
Transform Component
Switch to Scrip�ng
in the upper right-hand side of the browser window
as shown in the following screenshot:
13 ]What just happened?
Transform
page in the
Scrip�ng Reference
opens in the web browser as shown in the
following screenshot:
Actually, no. The whole reason for why the Scrip�ng Reference exist is so we can look for
informa�on as we need it. Which will actually happen us to remember the code we do
over and over, just like our other daily rou�nes and habits.
The previous screenshot shows a descrip�on and some sample code which probably doesn't
mean much right now. Fear not! You'll eventually be able to look at that and say, "Hey, I know
what that means!"
Un�l you learn
some basic programming concepts, it's too early to study how scripts work,
but we s�ll need to know how to create one.
There are several ways to create a script �le using Unity:
In the menu navigate to
Assets
Create
C# Script
Project
tab navigate to
Create
C# Script
Project
tab right-click , from the pop-up menu navigate to
Create
C# Script
From now on, when I tell you to create a C# script, please
use which ever method you prefer.
project progresses, we will have several folders to organize and store all of
Create a new Unity project and name it as
Right-click on in the
Project
tab and create a folder named
Right-click on the
folder and a create a folder named
folder, create a
Immediately rename
to
What just happened?
We created one
subfolders, named
, that we will be using to organize
our C# �les. This folder will contain all of our Unity script �les. Later we will create other C#
�le folders.
We also used Unity to create a C# script �le named
external editor to edit its C# scripts. Even though Unity can create a basic
starter C# script for us, we s�ll have to edit the script
MonoDevelop
code editor
that's included with Unity.
Syncing F# �les NePReen MonoGevelop Mnd UniPy
MonoDevelop are separate applica�ons, Unity will keep MonoDevelop and
Unity synchronized with each other. This means that if you add, delete, or change a script
�le in one applica�on, the other applica�on will see the changes automa�cally.
Unity will synchronize
with MonoDevelop the �rst �me you tell Unity to open a �le for edi�ng.
The simplest way to do this is just double-click on
in the
folder.
In Unity's Project tab, double-click on
What just happened?
MonoDevelop started with
open, ready to edit.
in Unity
No�ce line 4 in the previous screenshot:
is a requirement. You probably don't know what a class is yet, that's ok. Just remember that
the �le name and the class name must be the same.
When you create a C# script �le in Unity, the �lename, in the
Project
tab, is in Edit mode,
ready to be renamed. Please rename it right then and there. If you rename the script later,
the �lename and the class name won't match. The �lename would change, but line 4 would
This can easily be �xed in MonoDevelop by changing
on line 4 to the
same name as the �lename, but it's much simpler to do the renaming in Unity immediately.
So what happens when Murphy's Law strikes and syncing just doesn't seem to be working
correctly?
Should the two apps somehow get out-of-sync as you switch back-and-forth
between the them, for whatever reason, do this:
Right-click on Unity's
Project
window and select
Sync MonoDevelop Project
MonoDevelop will re-sync with Unity.
v1. As a beginner, what's the biggest obstacle to be overcome to be able to write C# code?
v2. The Scrip�ng Reference supplies example code and a short descrip�on of what the code
does. What do you use to get full detailed descrip�ons of Unity's Components and features?
v3. The Scrip�ng Reference is a large document. How much it should you know before
a�emp�ng to write any scripts?
v4. When crea�ng a script �le in Unity, when is the best �me to name the script �le?
17 ]Summary
This chapter tried to put you at ease about wri�ng scripts for Unity. You do have the ability
to write down instruc�ons which is all a script is, a sequence of instruc�ons. We saw how
simple it is to create a new script �le. You probably create �les on your computer all the
�me. We saw how to easily bring up Unity's documenta�on. Finally we had a look at the
MonoDevelop editor. None of this was complicated. In fact, you probably use apps all the
�me that do similar things. Bo�om line, there's nothing to fear here.
Alright, let's start o�
Chapter 2, Introducing the Building Blocks for Unity Scripts by having an
introductory look at the building blocks of programming we'll be using: variables, methods,
Dot Syntax, and the class. Don't let these terms scare you. The concepts behind each one of
these are similar to things you do o�en, perhaps every day.
for UniPy ScripPs
A programming language such as C# can appear to be very complicated at
first but in reality, there are two parts that form its foundation. These parts
are variables and methods. Therefore, understanding these critical parts is a
prerequisite for learning any of the other features of C#. Being as critical as
they are, they are very simple concepts to understand. Using these variable and
method foundation pieces, we'll be introduced to the C# building blocks used to
create Unity scripts.
For those people who get sweaty palms just thinking of the word script, wipe your hands and
relax. In this chapter, I'm going to use terms that are already familiar to you to introduce the
building blocks of programming. The following are the concepts introduced in this chapter:
Using variables in a script
Using methods in a script
The class which is a container for variables and methods
Turning a script into a Component
Components communica�ng using the Dot Syntax
Let's have a look at these primary concepts.
20 ]Using POe Perm mePOod insPeMd of funcPionYou are constantly going to see the words
method
used everywhere as
you learn Unity.
The words func�on and method truly mean the same
thing in Unity. They do the same thing.
Since you are studying C#, and C# is an
Object-Oriented Programming
) language,
I will use the word "method" throughout this book, just to be consistent with C# guidelines.
It makes sense to learn the correct terminology for C#.
Also, UnityScript and Boo are OOP
languages. The authors of the
Scrip�ng Reference
probably should have used the word
method instead of func�on in all documenta�on.
From now on I'm going to use the words method or methods in this book.
When I refer to the func�ons shown in the
Scrip�ng Reference
, I'm going to
use the word method instead, just to be consistent throughout this book.
What is a variable? Technically, it's a �ny sec�on of your computer's memory that will hold
any informa�on you
put there. While a game runs, it keeps track of where the informa�on
is stored, the value kept there, and the type of the value. However, for this chapter, all you
need to know is how a variable works in a script. It's very simple.
21 ]What's usually in a mailbox, besides air? Well, usually there's nothing but occasionally there
is something in it. Some�mes there's money (a paycheck), bills, a picture from aunt Mabel,
a spider,
and so on. The point is what's in a mailbox can vary. Therefore, let's call each
mailbox a variable instead.
Using the picture of the
country mailboxes, if I asked you to see what is in the mailbox, the
�rst thing you'd ask is which one? If I said in the Smith mailbox, or the brown mailbox, or
the round mailbox, you'd know exactly which mailbox to open to retrieve what is inside.
Similarly, in scripts, you have to name your variables with a unique name. Then I can ask
you what's in the variable named
, or whatever cool name you might use.
As you write a
script and make a variable, you are simply crea�ng a placeholder or a
subs�tute for the actual informa�on you want to use. Look at the following simple math
equa�on: 2 + 9 = 11
Simple enough. Now try the following equa�on: 11 +
There is no answer to this yet. You can't add a number and a word. Going back to the
mailbox analogy,
write the number 9 on a piece of paper. Put it in the mailbox named
. Now you can solve the equa�on. What's the value in
? The value
is 9. So now the equa�on looks normal: 11 + 9 = 20
variable is nothing more than a named placeholder to store some data
(informa�on). So anywhere you would like the number 9 to appear in your script, just
write
, and the number 9 will be subs�tuted.
Although this example might seem silly at �rst, variables can store all kinds of data that is
much more complex than a simple number. This is just a simple example to show you how
a variable works.
Let's see how this
actually works in our script. Don't be concerned about the details
of how to write this, just make sure your script is the same as the script shown in the
next screenshot.
Project
In MonoDevelop, write the lines 6, 11, and 13 from the next screenshot.
Save the �le.
To make this script work, it has to be a�ached to a GameObject. Currently, in our
State
project we only have one GameObject, the
Main Camera
since this script
doesn't a�ect the
Main Camera
in any way. The script simply runs by
virtue of it being a�ached to a GameObject.
Drag
onto the
Main Camera
Main Camera
so that it appears in the
Inspector
Verify whether
is a�ached.
panel to view the output of the script.
Play
The preceding steps are shown in the following screenshot:
What just happened?
In the following
panel is the result of our equa�ons. As you can see, the equa�on
on line 13 worked by subs�tu�ng the number 9 for the
variable:
is a variable, the value it stores can vary. If we change what is stored in it,
the answer to
the equa�on will change too. Follow the ensuing steps:
Stop the game and change
to
No�ce that when you restart the game, the answer will be
24
What just happened?
You learned that a variable works by simple process of subs�tu�on. There's nothing more to
it than that.
We didn't get into
the details of the wording used to create
variables you can create, but that wasn't the intent. This was just to show you how a variable
works. It just holds data so you can use that data elsewhere in your script. We'll get into the
�ner details of variables in
Chapter 3
Variables in Detail
Inspector
panel, try changing the value of
to some other value, even a
nega�ve value. No�ce the change in answer in the
25 ]3.   Save the �le.
In the previous screenshot, lines 6 and 7 will look familiar to you; they are variables just as
you learned
in the previous sec�on. There are two of them this �me. These variables store
the numbers that are going to be added.
Line 16 may look very strange to you. Don't concern yourself right now with how this works.
Just know that it's a line of code that lets the script know when the
Return
Enter
key is
pressed. Press the
Return
Enter
key when you want to add the two numbers together.
Line 17 is where the
method gets called into ac�on. In fact, that's
exactly how to describe it. This line of code calls the method.
20, 21, 22, and 23 make up the
method. Don't be concerned about
the code details yet. I just want you to understand how calling a method works.
26 ]The AddTwoNumbers() is the name of the method. Like a variable,
nothing more than a named placeholder in the memory, but this �me it stores some lines of
code instead. So anywhere we would like to use the code of this method in our script, just
write
, and the code will be subs�tuted.
Line 21 has an opening curly-brace and line 23 has a closing curly-brace. Everything between
the two curly-braces is the code that is executed when this method is called in
our script.
Look at line 17 from the previous screenshot:
The method name
is called. This means that the code between the
curly-braces is executed.
It's like having all of the code of a method right there on
Of course, this
method only has one line of code to execute, but a
method could have many lines of code.
Line 22 is the ac�on part of this method, the part between the curly-braces. This line of code
is adding the two variables together and displaying the answer to the Unity
follow the ensuing steps:
Go back to Unity and have the
panel showing.
Now click on
Play
What just happened?
Actually, as you sit
there looking at the blank
panel, the script is running perfectly,
just as we programmed it. Line 16 in the script is wai�ng for you to press the
Return
Enter
key. Press it now.
And there you go! The following screenshot shows you the result of adding two variables
together that contain the numbers 2 and 9:
Line 16 waited for you to press the
Return
Enter
key
. When you do this, line 17 executes
which calls the
method. This allows the code block of the method, line
23, to add the the values stored in the variables
Play
Main Camera
so its Components show in the
Inspector
Inspector
panel, locate
Learning Script
and its two variables. Change the
values, currently
, to di�erent values. Make sure to click your mouse in the
panel so it has focus, then press the
Return
Enter
key again. You will see the result of the
new addi�on in the
You just learned how a method works to allow a speci�c block of code to to be called to
perform a task.
We didn't get into any of the wording details of methods here, this was just to show you
fundamentally how they work. We'll get into the �ner details of methods in
Chapter 4
Ge�ng into the Details of Methods
play
s a major role in Unity. In fact, what Unity does with a class a li�le piece of
magic when Unity creates Components.
You just learned about variables and methods. These two items are the building blocks used
to build Unity scripts. The term script is used everywhere in discussions and documents.
Look it up in the dic�onary and it can be generally described as wri�en text. Sure enough,
that's what we have. However, since we aren't just wri�ng a screenplay or passing a note
to someone, we need to learn the actual terms used in programming.
Unity calls the code it creates a C# script. However, people like me have to teach you some
basic programming
skills and tell you that a script is really a class.
In the previous sec�on about methods, we created a class (script) called
. It contained a couple of variables and a method. The
main concept or idea of a class is that it's a container of data, stored in
variables, and methods that process that data in some fashion. Because I don't
have to constantly write class (script), I will be using the word script most of
the �me. However, I will also be using class when ge�ng more speci�c with
C#. Just remember that a script is a class that is a�ached to a GameObject.
28 ]In Chapter 7
Crea�ng the Gameplay is Just a Part of the Game
, we will be crea�ng some
classes for a State Machine. These classes will not be a�ached to any GameObjects, so I
won't be calling them scripts.
By using M liPPle UniPy mMgic, M scripP Necomes
While working in Unity, we wear the following two hats:
A Game-Creator hat
A Scrip�ng (programmer) hat
When we �rst wear our
Game-Creator hat, we will be developing our Scene, selec�ng
GameObjects, and viewing Components; just about anything except wri�ng our scripts.
When we put our Scrip�ng hat on, our terminology changes as follows:
We're wri�ng code in scripts using MonoDevelop
We're working with variables and methods
The magic happens when you put your Game-Creator hat back on and a�ach your script to
a GameObject. Wave the magic wand — ZAP — the script �le is now called a Component,
and the public variables of the script are now the proper�es you can see and change in the
Inspector
A script is like a blueprint or a wri�en descrip�on. In other words, it's just a single �le in a
folder on our hard drive. We can see it right there in the
Projects
panel. It can't do anything
just si�ng there. When we tell Unity to a�ach it to a GameObject, we haven't created
another copy of the �le, all we've done is tell Unity we want the behaviors described in
our script to be a
Component of the GameObject.
When we click on the
Play
bu�on, Unity loads the GameObject into the computer's
memory. Since the script is a�ached to a GameObject, Unity also has to make a place
in the computer's memory to store a Component as part of the GameObject. The
Component has the capabili�es speci�ed in the script (blueprint) we created.
Even more Unity magic
There's some more magic you need to be aware of. The scripts inherit from
For beginners to Unity, studying C# inheritance isn't a subject you need to learn in any great
detail, but you do need to know that each Unity script uses inheritance. We see the code in
every script that will be a�ached to a GameObject. In
, the code is on line 4:
The colon and the last word of that code means that the
class is inheri�ng
behaviors from the
class. This simply means that the MonoBehaviour
class is making few of its variables and methods available to the LearningScript class. It's
no coincidence that the variables and methods inherited look just like some of the code
we saw in the
Unity Scrip�ng Reference
The following are the two inherited behaviors in the
The magic is that you don't have to call these methods, Unity calls them
automa�cally. So the code you place in these methods gets executed automa�cally.
HMve M go Oero – �nding SPMrP Mnd UpdMPe in POe ScripPing Reference
Try a search on the
Scrip�ng Reference
for
Start
Update
to learn when each method is
called by Unity and how o�en.
Also search for
. This will show you that since our script inherits from
, we are able to use the
methods.
Our script has variables to hold data, and our script has methods to allow tasks to be
performed. I now want to introduce the concept of communica�ng with other GameObjects
Components they contain. Communica�on between one GameObject's Components
and another GameObject's Components using Dot Syntax is a vital part of scrip�ng. It's
what makes interac�on possible. We need to communicate with other Components or
GameObjects to be able to use the variables and methods in other Components.
When you look at the code wri�en by others, you'll see words with periods separa�ng them.
What the heck is that? It looks complicated, doesn't it. The following is an example from the
Unity documenta�on:
Don't concern yourself with what the preceding code means as that comes
later, I just want you to see the dots.
That's called the Dot Syntax. The following is another example. It's the �c��ous address of
my house: USA.Vermont.Essex.22MyStreet
Looks funny, doesn't it? That's because I used the syntax (grammar) of C# instead of the post
o�ce. However, I'll bet if you look closely, you can easily �gure out how to �nd my house.
We'll get into much more Dot Syntax detail in
Chapter 6
Using Dot Syntax for
Object Communica�on.
v1. What is the purpose of a variable in a script?
v2. What is the purpose of a method in a script?
v3. How does a script become a Component?
v4. What is the purpose of Dot Syntax?
Summary
This chapter introduced you to the basic concepts of variables, methods, and Dot Syntax.
These building blocks are used to create scripts and classes. Understanding how these
building blocks work is cri�cal so you don't feel you're not ge�ng it.
We discovered that a variable name is a subs�tute for the value it stores; a method name is a
subs�tute for a block of code; when a script or class is a�ached to a GameObject, it becomes
a Component. The Dot Syntax is just like an address to locate GameObjects and Components.
With these concepts under your belt, we can proceed to learn the details of the sentence
structure, the grammar, and the syntax used to work with variables, methods, and the Dot
Syntax. In the next chapter we will learn about the details of using variables.
Initially, computer programming appears difficult to beginners due to the fact
how words are used in code. It's not the actual words that cause the problem
because, for the most part, many of the words are the same words that we use
in our everyday life. C# is not a foreign language. The main problem is that the
words simply don't read like the typical sentences we are all used to. You know
how to say the words and you know how to spell the words. What you don't
know is where and why you need to put them in that crazy looking grammar,
that is, the syntax that makes up a C #statement.
In this chapter, we will learn some of the basic rules for writing a C# statement.
We will also be introduced to many of the words that C# uses and the proper
placement of these words in the C# statements when we create our variables.
In this chapter we will cover the following topics:
Wri�ng C# statements properly
Using C# syntax to write variable statements
The GameObject Component's proper�es
Using public variables for the Unity Inspector panel
Naming a variable properly
Declaring a variable for the type of data it will store
Ok, let's learn some programming grammar, otherwise known as C# syntax.
32 ]Writing C# statements properlyWhen you do normal wri�ng, it's in the form of a sentence with a period used to end the
sentence. When
you write a line of code, it's called a statement with a semi-colon used to
end the statement.
The reason a statement ends with a semi-colon is so that Unity knows
when the statement ends. A period can't be used because they are used in
the Dot Syntax.
The code for a C# statement does not have to be on a single line as shown in the
following example:
The statement can be on several lines. Whitespace and carriage returns are ignored, so if
you really want to, you can write it as follows:
But I recommend you to not write your code like this because it's terrible reading code
forma�ed like the preceding code. However, there will be �mes that you'll have to write
long statements that will be longer than one line. Unity won't care. It just needs to see the
semi-colon at the end.
Understanding Component properties in Unity's
GameObjects have some
Components that make them behave in a certain way. For instance,
Main Camera
and look at the
Inspector
panel. One of the Components is the
Camera
Without that Component, it will cease being a camera. It would s�ll be a GameObject in your
scene, just no longer a func�oning camera.
33 ]VMriMNles Necome FomponenP properPies
Any Component of
any GameObject is just a script that de�nes a class, whether you wrote
the script or the Unity's programmer did. We just aren't supposed to edit the scripts that
Unity wrote. This means that all the proper�es we see in
Inspector
are just variables of
some type. They simply store data that will be used by some methods.
Unity changes script and variable names slightly
When we add our script to a GameObject, the name of our script shows up in the
Inspector
Component. Unity makes a couple of small changes. You might have no�ced
that when we added
to
Main Camera
, Unity actually showed it in the
Inspector
Learning Script
. Unity added a space to separate the words of the name.
Unity does this modi�ca�on to the variable names, too. No�ce that the variable
is shown as
. Unity capitalizes the �rst le�er as well.
These displayed changes improve readability in
Inspector
Changing a property's value in the Inspector panel
There are
two situa�ons when you can modify a property value:
Play
During the development mode (not in the
Play
When you are in the
Play
mode, you will see that your changes take e�ect immediately in
real �me. This is great when you're experimen�ng and want to see the results.
When you are in the
Play
mode, you will see that your changes take e�ect
immediately in real �me. This is great when you're experimen�ng and want
to see the results. Write down any changes you want to keep because when
you stop the
Play
mode, any changes you made will be lost.
When you are in the development mode, changes you make to the property values will be
saved by Unity. This means that if you quit Unity and restart it again, the changes will be
retained. Of course you won't see the e�ect of your change un�l you click on
Play
The changes you make to the property values in the
Inspector
not modify your script. The only way your script can be changed is for
you to edit it in the script editor (MonoDevelop). The values shown in the
Inspector
panel override any values you had assigned in your script.
If you desire to undo the changes you've made in the
Inspector
panel, you can reset the values
to the default values assigned in your script. Click on the Cog icon (the gear) on the far right of
the Component script, and then select
Reset
as shown in the following screenshot:
I'm sure you're wondering what the word
means at the beginning of
a variable statement:
It means that the
variable will be visible and accessible. It will be visible as a property in the
Inspector
panel so that you can manipulate the value stored in the variable. It also means
it can be accessed from other scripts using the Dot Syntax. You'll learn more about the Dot
Syntax in
Chapter 6
Using Dot Syntax for Object Communica�on
Not all variables need to be
. If there's no need for a variable to be changed in
Inspector
panel nor be accessed from other scripts, it doesn't make sense to clu�er the
Inspector
panel with needless proper�es. In
, perform the following steps:
Change line 6 to the following:
35 ]2.   Change line 7 to the following:
Save the �le.
In Unity, select
Main Camera
What just happened?
You will no�ce in the
Inspector
panel that both proper�es,
are gone.
The preceding line
explicitly states that the
variable is to be
therefore the variable is no longer a property in the
Inspector
panel. It is now a
private variable to store data.
variable is no longer visible as a property either, but you didn't
specify it as
If you don't explicitly state whether a variable will be
, by default,
the variable will implicitly be
It is good coding prac�ce to explicitly state whether a variable will
So now when you click on
Play
, the script works exactly as it did before. You just can't
manipulate the values manually in the
Inspector
panel anymore.
Always use meaningful names for storing your variables. If you don't do that, six months
down the
line, you will be sad. I'm going to exaggerate here a li�le bit to make a point.
I will name a variable as shown in the following code:
That's a descrip�ve name. In other words, you know what it means by just reading the
variable, and so ten years from now when you look at that name, you'll know exactly
what it means. Now suppose instead of
named this variable as shown in the following code:
Sure, you know what
is, but would you know that it referred to a bear making a big
po�y in the woods? I know right now you'll understand it because you just wrote it, but
six months down the line, a�er wri�ng hundreds of other scripts for all sorts of di�erent
projects, you'll look at that and wonder what
meant. You'll have to read several lines
of code you wrote to try to �gure it out.
You may look at the code and wonder who in their right mind would write such a terrible
code. So take the �me to write a descrip�ve code that even a stranger can look at and know
what you
mean. Believe me, in six months or probably less, you will be that stranger.
You should begin a
variable name with lowercase because it helps to dis�nguish between
a class name and a variable name in your code. The Component names (class names)
begin with a capital le�er. For example, it's easy to know that
is a variable.
There are of course excep�ons to this general rule, and every programmer has a preferred
way to use lowercase, uppercase, and perhaps an underscore to begin a variable name. At
the end, you will have to decide upon a naming conven�on you like. If you read the Unity
forums, there are some heated debates on naming variables. In this book, I will show you
my preferred way, but you can use whatever is more comfortable for you.
Let's use the
same example again as follows:
You can see that the variable name is actually eight words squished together. Since variable
names can be only one word, begin the �rst word with a lowercase, and then just capitalize
the �rst le�er of each addi�onal word. It greatly helps to create descrip�ve names and s�ll
being able to read it. There's a word for this called
camelCasing
I already men�oned that for
variables, Unity's
Inspector
will separate each word
and capitalize the �rst word. Go ahead, add the previous statement to
and see what Unity does with it in the
Inspector
37
Declaring a variable and its type
Every variable
we want to use in a script must be declared in a statement. What does that
mean? Well, before Unity can use a variable; we have to tell Unity about it �rst. Ok then,
what are we supposed to tell Unity about the variable?
There are only three absolute requirements for declaring a variable and they are as follows:
We have to specify the type of data a variable can store
We have to provide a name for the variable
We have to end the declara�on statement with a semi-colon
The following
is the syntax we use for declaring a variable:
Let's use one of the
variables as an example; the following is how to
declare a variable with the bare minimum requirements:
The following is what we have:
Requirement #1
is the type of data that
can store, which in this case is an
, meaning an integer
Requirement #2
Requirement #3
is the semi-colon at the end
The second requirement of naming a variable has already been discussed. The third
requirement of ending a statement with a semi-colon has been discussed. The �rst
requirement of specifying the type of data will be covered next.
The following is what we know about this bare minimum declara�on as far as Unity
is concerned:
There's no
by default
It won't appear in the
Inspector
panel, or be accessible from other scripts
The value stored in
defaults to zero
The most common built-in variable types
only shows the most common built-in types of data that C# provides for us and
that variables can store.
Just these basic
types are presented here so that you understand the concept of a variable
being able to store only the type of the data you specify. The custom types of data that you
will create later will be discussed in
Chapter 7
Crea�ng the Gameplay is Just a Part of the
in the discussion of Dot Syntax.
The following chart shows the most common built-in types of data you will use in Unity:
ype
Contents of the variable
float
string
bool
A simple integer
, such as the number
A number with a decimal, such as the number 3.14
Characters in double quotes, such as,
“W
atch me go now
A boolean, either
or
true
false
There
are few more built-in types of data that aren't shown in the preceding
chart. However, once you understand the most common types, you'll have no
problem looking up the other built-in types if you ever need to use them.
We know the
minimum requirements to declare a variable. However, we can add more
informa�on to a declara�on to save our �me and coding. We've already seen some examples
of assigning values when the variable is being declared and now we'll
see few more examples.
Add some more
variables to
using the types shown in the previous chart.
While declaring the variables, assign them values as shown in the following screenshot. See
how they are presented in the
Inspector
panel. These are all
variables so they will
Inspector
What just happened?
The following screenshot shows what Unity presents in the
Inspector
The variables are displayed in
Inspector
panel with the values already set.
Where you declare a variable is important
You will be
declaring and using variables in many places in a script. The variables that I have
shown you so far are called
member variables
. They are members of the
class, not declared within any method. These member variables are the only variables that
have the op�on of being displayed in the
Inspector
panel or being accessed by other scripts.
So where in the class should the member variables be declared? This is another subject that
can lead to
heated discussions. Personally, I declare them at the top of a class �le before
any methods are declared so that I see them all in one place. Other people like to declare
variables close to the point of �rst use in a method.
Declaring your member variables at the beginning of a class may
give you a mental clue that these member variables can be used
everywhere in the script.
We will also be crea�ng variables in methods. These variables are called as
local variables
and are never displayed in the Unity's
Inspector
panel, nor can they be accessed by other
scripts. This brings us to another programming concept called
variable scope
Variable scope is a fancy way
of saying "Where in the script does a variable exist". The
following screenshot explains you the scope of variables:
You might have no�ced that the rectangular blocks start and end with curly-braces. Just
like the
method in
Chapter 2
Introducing the Building blocks for Unity
Scripts
, the code between the opening curly-brace and a closing curly-brace is called a
code
Absolutely anywhere in a code that you have an opening curly-brace, there will be a
curly-brace to match. All the code between the two braces is a code block.
41
No�ce that the code blocks can be nested inside other code blocks.
You normally don't just create bare blocks of code with curly-braces like I
. Code blocks are usually part of other things such
as if statements, looping statements, and methods. This example is just to
demonstrate how the scope of a variable works, and where a variable exists
The following is what you have:
The preceding line declares a local
variable named
. This variable exists in
the code block that is labeled
. If you try to use the variable
, Unity will give you an error message
saying that variable
doesn't exist.
The scope of the variable
is the code block de�ned by the curly-braces of lines 13
Now let's look at the
variable:
The preceding line declares a
type member variable named
. This variable
exists in the code
block that is labeled
. This code block begins on line 5 and
ends on line 20. This means the variable
can be used everywhere, including
because, they are also within
variable
The scope of the
variable is the code block de�ned by the curly-braces between
v1. What is the proper way to name a variable?
v2. How do you make a variable appear in the Unity's
Inspector
v3. Can all variables in a script show in the
Inspector
v4. Can a variable store any type of data?
42 ]Summary
We �rst covered how to write a C# statement, especially the semi-colon to terminate
a statement. All the Component proper�es shown in the
Inspector
panel are member
variables in the Component's class. Member variables can be shown in the
Inspector
or accessed by other scripts when the variable is declared as
. The type of data a
variable can store is speci�ed when it's declared. Finally, we learned that variable scope
determines where it is allowed to be used.
Now that we've learned about variables, we're ready to learn the details of C# methods that
will use the variables we create – which is the topic of the next chapter.
In the previous chapter, you were introduced to a variable's scope—where
a variable exists and is allowed to be used. The scope is determined by the
"opening" and "closing" curly braces. The purpose of those curly braces is to act
as a container for a block of executable code, a code block. In second chapter you
saw that a method is a code block that can execute by just calling the method's
name. It's time to see the importance of code blocks and the variables used in
them. A method defines a code block which begins and ends with curly braces.
In this chapter we will cover the features of methods:
Ending method de�ni�ons with curly braces
Using methods in a script
Naming methods properly
De�ning a method
Calling a method
Returning a value from a method
methods
Variables are the �rst major building block of C#, methods are the second, so let's dive
into methods.
44 ]Ending M mePOod de�niPion using curly NrMcesAt the beginning
Chapter 3
Ge�ng into the Details of Variables
you learned about C#
statements and the requirement to end them with a semicolon. A method de�ni�on has
a di�erent requirement.
A method de�ni�on ends with a code block between a pair of curly braces.
DO NOT
a method de�ni�on with a semicolon.
If you do accidentally place a semicolon at the end, MonoDevelop will gladly remind
you with an error message that you're not supposed to use a semicolon at the end
of a method de�ni�on.
All of the executable code in a script is in methods.
The �rst purpose of a method is to work with the member variables of the class. The
member variables store data that's needed for a Component to give a GameObject its
behavior. The whole reason for wri�ng a script is to make a GameObject do something
interes�ng. A method is the place we make the behavior come to life.
The second purpose of a method is to create code blocks that will be used over and over
again. You don't want to be wri�ng the same code over and over. Instead, you place the
code into a code block and give it a name so you can call it when needed.
You can look at those names and know exactly what the method is going to do.
45 ]Don't make them too simple. Suppose you name a method
. Sure you know what
Wiggle means right now, but in six months you'll look at that and say "Wiggle? Wiggle
what?" It only takes a moment to be a li�le more precise and write
Now when you see that method name, you'll know exactly what it's going to do.
46 ]TOe minimum requiremenPs for de�ning M mePOodThere are three
minimum requirements for de�ning a method:
The type of informa�on, or data, a method will return to the place where the
method was called
The name of the method should be followed by a pair of parentheses
A pair of curly braces should be present for containing the code block:
47
One thing for sure is that it makes easy to recognize that it's a method, but why are they part
of a method's name?
We
already know that a method is a code block that is going to get called mul�ple �mes. That's
one of the reasons why a method created in the �rst place, so we don't have to write the same
code over and over. Remember the AddTwoNumbers () method back in Chapter 2. It was very
simple method used to explain the concept of a method and how to call it. Now it's �me to
take the next step and learn the usefulness of the parentheses.
We're going to modify
to send some informa�on to the
method to make it much more useful.
Why would we need to send informa�on to a method?
A script may need to add two numbers several �mes, but they probably won't always be
the same two numbers. We could possibly have hundreds of di�erent combina�ons of "two
numbers" to add together. This means that we need to let the method know, which two
numbers need to be added together at the moment when we call the method.
48 ]Using the preceding screenshot, perform the following steps:
in MonoDevelop to modify it.
Add lines 6, 7, and 8 to declare three integer variables.
Add lines 22 to 26 to de�ne the
method with parameters.
Add lines 12, 13, and 14 to call the
three �mes.
Save the �le.
Play
in Unity.
What just happened?
As this script
executes, the
method is called three �mes on lines 12,
13, and 14. The method's code block adds two numbers and displays the result in the Unity
(see the yellow arrows in the following screenshot):
Those parentheses are like a
cubbyhole
. When we call
a couple of
numbers are stu�ed into the cubbyhole. When the code block executes, it takes those
two numbers held in the cubbyhole and uses them on line 24.
There's a special name for that informa�on between the parentheses of a method
de�ni�on, such as line 22—the code is called the method parameters.
Specifying M mePOod's pMrMmePers
If you look up the
word parameters in the dic�onary, your brain will probably seize up. All it
means is that the method has to be able to use the informa�on you send it, so you simply
have to specify the type of data the method is allowed to use. That's it, it's very simple.
In the earlier screenshot, on line 22 the red arrows pointed to the type of the declared
variables
. Now no�ce the
red arrow poin�ng to the variables
. They are also of the
. These variables have to be of type
since they store the numbers that will be
added in the method, which the parameters specify will be of type
49 ]So now go look in the dic�onary again. You will probably see the word limit in there
somewhere. That's what you did when you speci�ed the type of data, an integer, that the
method will use. You set some limits on what's allowed.
Ok, so you're se�ng parameters, or limits, on the type of data the method can use, but
what exactly is a parameter? Well, the �rst parameter is called
, and what is
doing? It's storing a value that will be used in the code block on line 24. What
do we call things that store data? That's right, variables. Variables are used everywhere.
Remember, a variable is just a subs�tute name for the
value it actually stores.
As you can see
on line 22 of the code block, those variables are being added together.
50 ]Yup, that explains it totally, right? Ok, let's really learn what arguments are, and what they do
in code. In the previous screenshot, look at line 12:
Between the
parentheses are the variables,
. Those two variables
are called the arguments that are being passed to the method. In simple terms, the values
stored in these two variables, 2 and 3, are placed in the cubbyhole.
On line 22, the method de�nes that it takes in two parameters called
. This means, of course, that somewhere in this process these parameters
will have to have values assigned them.
Here's the secret I �nally discovered on my own. Behind the scenes, where you can't see,
the values 2 and 3, that are in the cubbyhole, are now assigned to the variables
You don't see this code, but if you could see it, what happens with arguments and
parameters looks just like this:
Since the argument
contained the value 2, now the parameter
contains the value 2
Since the argument
contained the value 3, now the parameter
contains the value 3
Now the code block is executed and the value 5 is displayed in the Unity
As you can now see, the names of the arguments and the names of the parameters don't
need to be the same. They're just names of variables used in di�erent places in your code.
They're just subs�tutes for the actual values each contain, and it's the value that's ge�ng
transferred from the method call to the method code block.
Now it's �me to
discover the "power" feature of using a method. This usually means sending
data to the method, which you just learned to do, then have the method return a value back.
Previously, all you had the
method do was take the result of adding two
numbers and display it to Unity's Console.
Now, instead of displaying the result directly, you're going to modify
to return the result of the addi�on back to the place the method was called.
51
Remember, I told you that when you call a method, it's just a subs�tute
for the code block that will be executed. It's like taking all the code in the
method's code block and placing it right there where the method was called.
The next screenshot is
s�ll very simple, but it shows how this subs�tu�on works and
how returning a value from a method works.
Time for McPion – rePurning M vMlue from AddTRoNumNers()
Modify
to call the
method twice and get a grand
total. Also create another
method whose sole purpose is to display the grand total result.
in MonoDevelop to modify it.
On line 12, declare the answer variable (this statement is on 3 lines).
On lines 19 to 23, rede�ne the
method with a return type.
On lines 25 to 28, de�ne the
method.
Save the �le.
Click on Play in Unity.
52
What just happened?
As you can see
in the following screenshot, the result is
. However, the main concept
to learn from this example is this:
When a method returns a value, it's a type of data just like a variable would store
In fact, the value returned from a method could easily be stored in a variable
Analysis of the code is as follows:
The code on line 10 and its descrip�on is as follows:
Unity calls the
method once only.
The code
on lines 12 to 14 and its descrip�on is as follows: (Note: I have put this
single statement on three lines for a be�er screenshot.)
All this line does is add two numbers and store the result in a variable
named "answer".
First there is a call to
The arguments
send the integers 2 and 3 to the method
parameters on line 19.
The code on line 19 and its descrip�on is as follows:
The integers 2 and 3 are assigned to the parameter variables
The code on line 21 and its descrip�on is as follows:
The numbers 2 and 3 are added and stored in the declared variable result.
53 ]‹‹‹ ‹The code on line 22 and its descrip�on is as follows:
The code on line 25 with its descripton:
The integer 14 is assigned to the parameter variable total.
The code on line 27 and its descrip�on:
This output to the Unity
includes a li�le peek into the next chapter.
Some text is displayed as well as the value stored in the variable total.
displays
The grand total is: 14
method is done execu�ng its code. Since there is no further code
to execute, the script is done.
Try modifying line 12 to add the numbers together that are stored in the variables
. You will have to include an addi�onal call to
. The result in
The grand total is: 24
55 ]Here's just a por�on of the methods Unity can call in a script. This is from the
Scrip�ng
Reference
. Just search for
Look at line 4 of
LearningScript
This line says that
inherits from
. Any script that inherits
from
will automa�cally call the methods
if they are
in the script. Therefore, if you want, you can create a script in MonoDevelop instead of Unity,
just have it inherit from
by adding:
a�er the class name.
colon
that needs to be included.
called every frame, it allows your game to detect input, such as mouse
clicks and key presses, every frame. User input is one of the topics we are about to cover in
the next chapter.
v1. What are the minimum requirements for de�ning a method?
v2. What is the purpose of the parentheses at the end of the method's name?
v3. What does void mean in a method de�ni�on?
v4. In a Unity script, how is the
called?
Summary
In this chapter, we learned that a method de�ni�on ends with a code block between two
curly braces, not with a semicolon. The parentheses are part of a method's name. We also
learned how to call a method into ac�on, how to use data returned from a method, and
that Unity calls some methods automa�cally, such as the
methods,
when the script inherits from the
You now know the two major building blocks of scrip�ng, variables and methods. From now
on, everything else you do will just be making use of variables and methods. Now that you
understand these two building blocks, you are ready for the next chapter that deals with
making decisions in your code.
One of the primary duties of a computer is controlling what happens next
when certain conditions are met. That's what computers do whether the code
is controlling an application or a game. We write scripts to make GameObjects
behave a certain way one moment, then the behavior should change when the
conditions change. A script has to detect when the conditions change, then
make the appropriate code execute based on the new conditions. This chapter
looks at some examples of the ways that conditions can change, and the code
to detect these changes. This in turn determines which code in the script is
executed next.
In this chapter we will discuss:
If statement decisions
Checking for many condi�ons
If-else statement decisions
User's input condi�on changes
Looping though data in an Array, List, or Dic�onary
Let's begin...
TesPing condiPions RiPO Mn if sPMPemenP
If, if, if. If I do this… if I do that… What happens if…
Certainly
you've had to make decisions about all kinds of things in your life every day. We all
do it all the �me without actually giving the process of making a decision much thought, if
any. As we make daily decisions, most of the �me we just do the decision processing in our
head. Unity doesn't have that human luxury, so we have to write it out so
Unity can know
the condi�ons that lead to certain choices. Having to write the logic is the strange part of
wri�ng code for beginners, simply because people usually make the vast majority of decision
without wri�ng anything down �rst. However, it is very simple to do.
statement is
the most common way GameObjects make decisions. Data used to make
these decisions is the informa�on usually stored in some variables. For an if statement it's as
easy as saying "If my condi�on is met, then execute my code block."
TesPing if condiPions Mre Prue or fMlse
condi�ons that can be true or false:
The user pressed a bu�on
The temperature is cold
The character died
The bear made big po�y in the woods
General ques�ons like these are answered by humans, usually, with either a yes or no. For
Unity, the answers will be either true or false. For example: "the bear made big po�y in the
woods" is either true, or false.
statements work
by determining whether a condi�on inside a pair of parentheses is
true or false.
Modify
as shown in the next screenshot.
Save the �le.
In Unity, click on Play.
What just happened?
Here's the output in the
Code analysis:
The code on line 8 is as follows:
This Boolean variable is declared and assigned the value of
The code
on line 10 and its descrip�on:
statement to test if the condi�on between the parenthesis is
The variable
is storing a value
therefore.The code block on lines 11 to 13 is executed, as shown in the
screenshot.
Here's a li�le curveball to wrap
your mind around, the NOT logical operator. It's wri�en in
code using an exclama�on mark. This makes a true condi�on false, or a false condi�on true.
The code on line 15 along with its descrip�on:
Assigns the value
to
The code on line 17 with its descrip�on is as follows:
Another if statement, but this �me
is false.
However, there's a NOT logical operator in front of the variable. See the exclama�on
mark in the red circle shown in the previous screenshot.
This means the if statement condi�on is NOT false, which is the same as saying
true. Therefore the code block on lines 18 to 20 will be executed, as shown in
the Console screenshot
The code block on lines 18 to 20 will be executed, as shown in the Console screenshot
I can already hear your ques�on, why not just check for true? As you will discover when
wri�ng if statements, you need to be able to make decisions based on whether a condi�on
is true, or if the condi�on is false. You want the op�on to execute a code block for either of
these two condi�ons. For example, you may want to execute some code based on whether
a user didn't press a bu�on at a par�cular �me. If the user did not press the bu�on, then
execute the code block.
Some�mes you will want your if statements to check many condi�ons before any code block
is executed.
This is very easy to do. There are two more logical operators that you can use:
AND: It is used by pu�ng
between the condi�ons being checked.
OR: It is used by pu�ng
between the condi�ons being checked.
Modify
as shown in the next screenshot.
Save the �le.
In Unity, click on Play.
No�ce line 11 is using the AND operator, and line 16 is
using the OR operator.
What just happened?
Here is the output you get in the Unity
analysis:
The code
on line 8 and its descrip�on:
variable is declared and assigned the value of
The code on line 9 with its descrip�on:
variable is declared and assigned the value
62
The code on line 11 with its descrip�on:
statement to test if both condi�ons are
The �rst test is checking if the
is greater then, or equal to,
The value stored in
, so this condi�on is true.
The value stored in
is true. Therefore the �rst
condi�on and the second condi�on are true, so the code block executes.
The code on line 16 with its descrip�on:
statement to test if either of the condi�ons are true.
We already know that both the condi�ons are true, and either the �rst condi�on
or the second condi�on needs to be true. Therefore the code block will execute.
Try changing
to a lower value such as
. Only one of the
statements will
The following is the analysis of code:
The code
on line 11 and its descrip�on is as follows:
Only one of the condi�ons is now true, as 30 is not greater then, or equal to, 35.
Therefore the �rst condi�on is false. Since both condi�ons have to be true, the
code block does not execute.
The code on line 16 and its descrip�on:
Only one of the condi�ons is now true.
30 is not greater then or equal to 35, therefore the �rst condi�on is false.
The second condi�on is true.
Since only one of the two condi�ons has to be true, doesn't make any di�erence
which one, the code block executes.
HMve M go Oero – cOMnge POeBeMrMMdeBigPoPPyHnTOeJoods Po fMlse
Now change
to false as well. Now you see that
neither of the if statements will execute their code blocks.
So far, the
statements have needed certain condi�ons to be
for the code block to
execute. There is an
op�on that allows you to have an alternate code block execute when
statement condi�ons are
If my condi�ons are met, execute the following code block, else execute the
alternate code block
This is very simple concept, just like a li�le kid saying: "If you give me an ice
cream cone, I'll be nice, else I'm going to be naughty."
if-else statements
are just like regular
if statements
op�on added.
Modify
as shown in the next screenshot.
Save the �le.
64 ]3.   In Unity, click on Play.
Line 14 shows how
, and its code block is simply added a�er the
code block.
What just happened?
The analysis
of code is as follows:
The code on line 8 and its descrip�on:
The variable
is assigned the value of false.
The code on line 10 and its descrip�on:
Since the condi�on is false, the code block on lines 11 to 13 is not executed, and the
script con�nues to line 14 of the if-else statement.
Therefore, the code block on lines 15 to 17 is executed instead:
v1. Humans can answer ques�ons with a yes or no. What do C# if statements need
as answers?
Q2. What logical operator can turn a
condi�on into
condi�on
into
v3. If two condi�ons have to be
to make an if statement's code execute, what logical
operator would you use to join the condi�ons?
v4. If only one of two condi�ons needed to be true to make an if statement's code execute,
what logical operator would you use to join the two condi�ons?
always have to be made when the user provides input. In
Chapter 2
Introducing
the Building Blocks for Unity Scripts,
we used an example where the user had to press the
Return/Enter
key to call the
method:
A�er the
No�ce that the code,
, isn't between two curly braces.
When there is only one line of code to execute for an if or an else, you have
the op�on to not use the curly braces.
66 ]SPoring dMPM in Mn MrrMy, M IisP, or M GicPionMry
There are �mes that many items need to be stored in some type of list. Perhaps a selec�on of
weapons that a character may use. An example used later in this book is a list of splashscreens
for the State Machine project we will build.
There are basically two
ways to access items in a list:
Direct retrieval
: The loca�on of an item in the list is already known, so code is
wri�en to access it directly, or
Loop retrieval
: The loca�on of an item in the list is not known, it's just in there
somewhere, so code is wri�en to loop through the list un�l the item desired is found.
First though, we need a list of items before we can select anything from the list. An example
of collec�ng items into a list, then looping through the list, is shown in the
Scrip�ng
Reference
67
As per the code on line 1:
‰‰‰ ‰public means this array will appear in the
Inspector
. Also the array is
accessible from other scripts.
is the type of variable being created. It's going to be a
Scripting Reference
The square brackets specify that the variable created is going to be an array,
a variable with many cubby-holes to store several
is the name of the array being created.
That was easy enough. It's just like crea�ng any other variable. The only di�erence
was the addi�on of the square brackets to specify that the type of variable being
declared is actually going to be an array.
Now that the array is created, the
Please no�ce that the very �rst index number starts with zero. This is called
zero indexed. It's just something you will have to remember. Many things in
programming are zero indexed, and it creates coding errors when you forget,
especially for beginners.
That's all I want to say about using arrays to store objects because I want to discuss using
instead. It's like an array with extra bene�ts.
instead of
an array can be so much easier to work with in a script. Look at
some forum sites related to C#, and Unity, and you'll discover that a great deal of
programmers simply don't use an array unless they have to, they prefer to use a
Here are the basics of why a List is be�er, and easier, to use than an array:
An array is a �xed size and unchangeable
The size of a
is adjustable
You can easily add to, and remove elements from a
To mimic adding a new element to an array, we would need to create a whole
new array with the desired number of elements, then copy over the old elements
The �rst thing to understand is that a
has the ability to store any type of object,
just like an array. Also, just like an array, we must specify, which type of object you want
to store.
This means that if you want a
of integers, of the
then you can create a
that will store only the
type. Want a
of pony names?
Then create a
that will store only the
Create a
that stores
the names of some ponies. Since they are names, use
Modify
as shown in the next screenshot.
No�ce the change on line 2.
Save the �le.
69 ]4.   In Unity, click on Play.
What just happened?
The following
screenshot is the
output. No�ce the �rst output tells you there is a
total of 3 elements in the
Please no�ce that your code is using dot syntax, which will be discussed in
more detail in the next chapter. The main concepts I want you to focus on
here are the features of a
The analysis of
code is as follows:
The code on line 2 is as follows:
To be able to use a
, this tells Unity where to �nd the necessary C# code �les
for using a
Change the using statement to
The code on line 8 is as fololws:
This statement creates an empty
First thing to no�ce is that
speci�es that you are crea�ng a
Everything on the le� side of the assignment operator (
) is crea�ng a variable,
Everything on the right side is just like assigning a value to a variable, therefore
is a method called to create a new
object in computer
memory, and give that memory loca�on the name of
What is
different here is that
is an object that itself can store data in
elements. Imagine an egg carton as an object that can store the egg type.
Creating objects will be discussed more in the next chapter about dot syntax.
71
The code between lines 10 to 12:
These three lines of code are adding
, the pony names, to the
Just like an array, each pony name
added is given an index number for
the element that each pony name is stored in:
avoriteP
onies
Cadence
Inde
x 0
Inde
x 1
Inde
x
Nightmare
Moon
The code on line 14 is as follows:
retrieves the number of elements in the
The code between lines 16 and 18:
)Here you see the index number inside square brackets. Just like an array, this is how
to directly retrieve the data in an element at a speci�c index.
Like the
array, the �rst element in a
is at index 0.
Add another pony to the
, then display it's name. Also, in the
, display the
number of elements in the
a�er adding the fourth pony.
Adding an element to the
shows the �exibility it has over an array.
to do using an array.
73
Storing items in a Dictionary
A dic�onary has a Key/Value pair. The
Key
is just like an index in an array or list, it's associated
par�cular value. The big bene�t of a dic�onary is that we can specify what the key is
going to be. We have to specify the type and the name of the key that will be associated with
the value stored.
A real world example you're familiar with is a collec�on of customers and their ID number.
Just by knowing the customer's ID, you could retrieve the customer's informa�on.
Time for McPion – creMPe M dicPionMry of pony nMmes Mnd keys
Create a
for the keys.
Modify
as shown in the next screenshot.
Save the �le.
In Unity, click on Play.
74
What just happened?
Here is the
output to Unity's
The analysis
of code is as follows:
The code on line 8 is as follows:
is very similar to declaring a
requires you to specify the type for the
This example used integers for the keys.
The code on lines 10 and 11 is as follows:
Here you added two ponies using
, just like you did for a
The code on lines 12 and 18 with its descrip�on is as follows:
myFavoritePonies[40] = "Rainbow Dash";Here you added ponies by assigning the pony name to a par�cular dic�onary key.
Using a Collection Initializer to add items to a List or Dictionary
There is another way to
add elements to a List or Dic�onary. So far you have declared and
created a new empty List and Dic�onary, then added ponies to them on separate lines of
code. You can add the ponies at the same �me
you declare the List or Dic�onary with a
Collec�on Ini�alizer.
If we know the items to add ahead of �me, we can add them when we create the
Modify
as shown in the next screenshot.
Save the �le.
In Unity, click on Play.
76 ]What just happened?
Here's the
The analysis of the code is as follows:
The code on lines 8 and 9 with its descrip�on:
This is actually a single statement. It's on two lines to make it �t the screenshot.
Line 9 shows the
Collec�on Ini�alizer
that's been added to the usual
declara�on.
No�ce the pony names are between two curly braces. This is not a code block.
This is another use of curly braces.
Collec�on Ini�alizer is the two curly braces and the strings, the pony
names, that are between them.
No�ce there is a semicolon a�er the last curly brace. This ends the
declara�on
statement.
The code between lines 14 and 15:
This is a single statement. It's on two lines to make it �t the screenshot.
Line 15 shows the
Collec�on Ini�alizer
that's been added to the usual
declara�on.
Each key and value pony name is between two curly braces, then all the
key/value pair combina�ons being ini�alized are between two curly braces.
77
v1. In an array or a List, what is an element?
v2. In an array or a List, what is the index number of the �rst element?
v3. Can a single array, or a single List, store di�erent types of data?
v4. How can you add more elements to an array to make room for more data?
These previous array, List, and Dic�onary examples showed how
to get data into them,
and how they store data. It's now �me to learn how to loop through the data to retrieve
the needed data.
Here are some common ways to perform loops:
When working with Collec�ons such as an array, a list or dic�onary, the preferred way to
cycle through the elements and retrieve data is to use the
We're going to
create an array, a list and a dic�onary, then loop through each one to retrieve
the desired data from each one by using
loops.
Modify
as shown in the next screenshot.
Save the �le.
78 ]3.   In Unity, click on Play.
What just happened?
As we looped
through each list, we decided which data to display to the
79 ]The analysis of the code is as follows:
For each
list we created, we populated them using a Collec�on Ini�alizer.
The code between lines 9 and 10 with its descrip�on:
A string array named
is declared and two strings are added.
The code on line 12 with its descrip�on is as follows:
loop is used to retrieve one element, a pony name string, stored
A variable is declared named
to hold the retrieved pony name.
Once a pony name is retrieved, the
code block, lines 13 to 16, is executed.
This looping con�nues un�l each element in
has been retrieved and
tested in the code block.
The code on line 14 with its descrip�on is as follows:
If the retrieved string stored in
is equal to
, then line 15 executes.
The code on line 15 with its descrip�on is as follows:
The string I was looking for plus the string value stored in pony is displayed in
The code between lines 18 and 19 with its descrip�on:
is declared that will store the
type, and two
strings are added.
The code on
line 21 with its descrip�on is as follows:
loop is used to retrieve one element, a pony name
, stored
A variable is declared named
to hold the retrieved pony name.
80 ]Once a pony name is retrieved, the
code block (that is, lines 22 to 25)
is executed.
This looping con�nues un�l each element in
has been retrieved and
tested in the code block.
The code on line 23 with its descrip�on is as follows:
If the retrieved string stored in
is equal to
24 executes.
The code on line 24 with its descrip�on is as follows:
The string I was looking for plus the string value stored in
is displayed
The code between lines 27 and 28 with its descrip�on:
is declared with key and value of type
, and two key/value pairs are added.
The code on line 30 with its descrip�on is as follows:
loop is used to retrieve one
, a key and value, stored in
A variable is declared named
to hold the retrieved
Once a key value and a pony name string are retrieved, the
code block
(that is, lines 31 to 34) is executed.
This looping con�nues un�l each
retrieved and tested in the code block.
The code on lines32 with its descrip�on is as follows:
If the retrieved
stored in pony is equal to
, then line 33 executes.
The code
on line 33 with its descrip�on is as follows:
The string
plus the string value stored in
displayed in the
The best descrip�on
I've found for a
loop: "Allows a code block to be executed a speci�c
The syntax of a
No�ce the three parts inside the parentheses are
separated by semicolons, not commas.
Let's add four
pony names to a
. Retrieve and display the number of elements in the
loop to display each pony name, and select one of them:
Modify
as shown in the next screenshot.
Save the �le.
In Unity, click on Play.
82 ]What just happened?
The following
screenshot shows the number of elements in
ponies we added to
, and the pony we were looking for:
The analysis of the
code is as follows:
The code between lines 8 and 9 with its descrip�on:
is declared that will store the
Four strings are added of the pony names.
The code on line 11 with its descrip�on is as follows:
The string
plus the number of elements
is displayed in the
is using dot syntax to access the
property, a variable
that stores the number of elements in a
Four names were added to
, so it has four elements to store the
string names.
83 ]‹‹‹ ‹The code on line 13 with its descrip�on is as follows:
is created.
The ini�alizer is simply a declared variable that's assigned a value.
We declared a variable
, and assigned it the a value of
. Why?
The �rst index number in a
The condi�on is checked for true before the code block, lines 14 to 19, is allowed
to be executed.
loop �rst begins, the variable
is equal to
is equal to
, therefore
. Therefore the
loop code
block is allowed to execute.
The iterator,
, now adds 1 to
now equal to
, which means that you are taking the
value in
and adding 1, then assigning that to
The loop repeats un�l the condi�on becomes
A�er four �mes through the loop,
is now equal to 4, therefore the condi�on is
now
because
, so the loop is �nished.
The le�er "i" is typically used as the variable name in a for loop. It's tradi�on. If
you happen to have nested for loops, then the variable names used will be the
le�ers j, k, l, and so on, as needed.
The code on
lines 15 with its descrip�on is as follows:
)The elements in
are being access using the index number.
loop is executed for the �rst �me,
is equal to
, therefore
is actually ponyList[0], the element at index 0.
The element at index 0 is storing
A�er each itera�on through the
loop, 1 is added to
, therefore the next trip
through the for loop,
will actually be ponyList[1], the next element at index 1.
The result is all four ponies will be accessed and displayed in the
The code on lines 17 with its descrip�on is as follows:
)During each itera�on through the code block, this if statement is checking to see if
the name retrieved from
is equal to "
When it is, line 18 is executed.
The code on lines 18 with its descrip�on is as follows:
)The string
is displayed in
loop executes a
code block un�l a speci�ed expression evaluates to false.
loop is very similar to a for loop. It's like breaking the
loop into component parts:
We're going to do something a li�le di�erent in this loop. Once we �nd the pony we want,
we'll breakout
of the while loop. This is handy when looping through a large list of objects.
When the desired data is found, there's no sense in con�nuing to loop
through the rest of
the list:
Modify
as shown in the next screenshot.
Save the �le.
In Unity, click on Play.
What just happened?
If we have
been searching for
instead of
, and not included the
keyword on line 19, the output would have been exactly
the same as the
loop
example. In fact, the
keyword could have also have been used to breakout of the
for loop.
86 ]I will skip explaining lines of code that are iden�cal in the
loop example.
The analysis of the code is as follows:
The code on line 11 with its descrip�on is as follows:
The ini�alizer is declared and assigned the value of 1.
The code on line 12 with its descrip�on is as follows:
loop is declared with the condi�on.
, the condi�on is true.
loop code block (that is, lines 13 to 22), is executed.
The code on line 16 with its descrip�on is as follows:
)During each itera�on through the code block, this
statement is checking to
see if the name retrieved from
is equal to
When it is, the code block of lines 17 to 20 is executed.
When it isn't, line 21 is the next line that is executed.
The code on line 21 with its descrip�on is as follows:
The iterator
is incremented by 1 and the loop repeats back to line 12 to check
the condi�on again.
The loop repeats un�l
is equal to 4, making the condi�on false which exits
The code
on line 18 with its descrip�on is as follows:
)The string
displayed in the
The code
on line 19 with its descrip�on is as follows:
is a C# keyword that alters code �ow.
Code execu�on immediately leaves this
loop code block and con�nues to the
�rst statement following the code block.
There is no statement following the while loop, the script is �nished.
On line 16, change the pony name being searched and observe how it changes the number
of pony names displayed in the
before stopping.
Summary
There are unlimited ways to make decisions in code, however, we covered many of the
common ways. The if statement is how the majority of decisions are made, including the
if-else statements. Then we covered some of the sources that require making decisions, like
user input, and using loops to evaluate data stored in arrays, lists and dic�onaries. None of
this is complicated. It's just a process of simple, logical steps.
Now that we've learned about the fundamentals of programming for wri�ng scripts, it's �me
to dig into the world of objects. Since everything in Unity is an object, you need to know how
to access the Components of an object, and how to communica�on between objects, by
using dot syntax. You have seen some dot syntax used already in the examples we've coded.
In next chapter, you will see how those dots work.
Scripts do many things by accessing the features built into Unity and third-party
plugins. The Unity Scripting Reference is our link to the built-in Unity features.
The thing is, exactly how do we invoke all of those Unity features?
So far all we've covered is basic C# programming. Granted, the example code
we've seen has included some Dot Syntax, such as Debug.Log() to send output
to Unity's Console. This is one of those Unity features. In the last chapter, we
even saw some more Dot Syntax, pony.Key and pony.Value, which has nothing
to do with Unity. These are just C# OOP (Object Oriented Programming)
related features.
In both cases, there's some type of communication taking place to access
methods and data to make things happen. To the beginner, those dots maybe
odd looking and confusing, and they may ask, "What's the deal with all those
darn dots between words?" Well, if you've been using the Internet and paid any
attention at all, you've been using those dots, probably for years, and didn't
pay much attention to them.
We see how to access the power of Dot Syntax as we cover the following sec�ons:
Dot Syntax being just an address
Working with objects
Using Dot Syntax in a script
Accessing GameObjects using drag-and-drop versus wri�ng code
So let's get on with it...
ost Office Syntax
err
y Norton
x, VT
err
y Norton
Specific
Looking at that,
Dot Syntax isn't so confusing. It's just an address in a di�erent format, in a
way to
locate things. Here's an example: imagine we met in Europe somewhere, and I ask
you to get my sunglasses using only this informa�on:
USA.Vermont.Essex.22 myStreet.2ndFloor.o�ce.desk.center drawer.sunglasses
Would you have any problem loca�ng them?
91 ]Using Mccess modi�ers for vMriMNles Mnd mePOodsI could foresee one
big issue trying to retrieve my
sunglasses. My house isn't open to
the public; it's a private residence, so the door is locked. This means you don't have access
to the sunglasses.
The same rules of access apply to member variables and methods of a class or script.
In C#, when we create a member variable or method in a script, it is private by default.
We can also explicitly specify that it's
Here,
A variable will not show in the
Inspector
as a Component property
The variable or method will not be accessible from other scripts
We can specify a variable or method to be
Here,
A variable will show in the
Inspector
as a Component property
The variable or method will be accessible from other scripts
Dot Syntax is
the system used to locate and communicate with a variable
or method in an
object. To understand how to use Dot Syntax, we have to know the rela�onship between
A script always has access to its own member variable and methods whether
they're
I'm throwing the word
around like you were born with the knowledge of what an
object is. Actually you do know what it means. The co�ee cup you may have in your hand
is an object, a real one. That UFO �ying around at night is an object; even if you can't
iden�fy it. In Unity, you may have a �ying saucer in your Scene, but it's obviously not a real
�ying saucer, it's a virtual one. However, in the virtual world of gaming, most people would
consider things they can see on the screen as objects.
If you can expand your mind just a li�le bit more, perhaps you can accept that not all objects
in Unity have to be something you can see in a game Scene. In fact, the vast majority of
objects in Unity are not visually in the Scene.
92 ]In a computer, an object is just a small sec�on of your computer's memory that acts like a
container. The container can have some data stored in variables and some methods to work
with the data.
The best example I can show you is the object you've been using since you started this book.
In MonoDevelop, we've
been working with the script called
. In Unity we
use the general term
Script
, but it's actually a class, which means it's a de�ni�on of a type of
container. Look at line 4 of the �le:
See that second word? That means that
is a class. In this class, we de�ned
its member variables and methods. Any variable not declared in a method is a member
variable of the class.
Chapter 2
Introducing the Building Blocks for Unity Scripts
I told you about the magic that
happens when we a�ach the script (class) to a GameObject. Shazam!! The script becomes a
Component object, a type of container for the GameObject that we de�ned as having some
variables to store data and some methods to work that that data.
Besides the visual mesh in the Scene, can you visualize in your mind that a GameObject is
just a bunch of di�erent types of Component objects assembled together to construct that
Each of those individual Components shown in the
Inspector
will become an object in our
computer's memory when we click on the
Play
bu�on.
Select any GameObject in the
, then look at the
Inspector
. For example, select
Main Camera
GameObject. There are several Components on the
Main Camera
GameObject. Look at each of those de�ned Components. Every one of those Components
started o� as a class �le in Unity, de�ning a type of container of variables and methods.
We don't see or modify those Unity class �les, but they're in Unity somewhere.
The name of the class is also known as the object type of the object that will be
created in memory from that class, when the
Play
bu�on is clicked.
Just like an
is a type of data, the name of a class is also a type
of data.
This means that when we declare a variable and specify the type of data it will store,
it can just as easily store a reference to an object of the
shown in the following line of code:
93 ]‹‹‹ ‹Storing a reference to an object in a variable does not mean we are storing the
actual object. It means we are storing the loca�on in memory of that object. It's
just a reference that points to the object in memory so that the computer knows
where to access the object's data and methods.This means we can have several
variables storing a reference to the same object, but there's s�ll only one actual
object in memory.
A script
is just a �le on your hard drive, and there's only ever one �le. The class
�le simply de�nes a type of container of variables and methods that will become
a Component object in the memory when you click on
Play
. You can a�ach the
script to many GameObjects, but there's s�ll only one �le on your hard drive.
A�aching a
Script
to a GameObject is like placing a s�cky-note on the GameObject. When
we click on the
Play
bu�on, Unity looks at our GameObject, sees the s�cky-note which says,
"This GameObject is supposed to have a Component of type
. Make some
room in the computer's memory to hold this object of variables and methods as described in
If we were to a�ach
to 1000 GameObjects, and click on
Play
, there will
be 1000 separate sec�ons created in your computer's memory that each stores an object
. Each one has its own set of variables and methods, as described
by the
�le. Each one of those 1000 sec�ons of computer memory is a separate
Component object of its respec�ve GameObject.
Even though the object created from a class is called a Component by
Unity; in more general C# terms, each object that gets created from a
class is called an instance object. A Component object and an instance
object are the same thing.
Now that you know that
each Component object resides in computer memory, storing
data
in variables, it's �me to use Dot Syntax to access those Component variables and methods.
In order to have access to a variable or method, we have to know its loca�on. Let's start by
Here's an overview of how to access a variable or method from within the current Component:
current Component
To
access the item in
:
bold
Let's look at accessing a
variable in
from inside
Modify
as shown in the following �gure:
95 ]2.   Save the �le.
In Unity,
Play.
What just happened?
Here are the outputs in the
An analysis of the code shown in the previous code screenshot is as follows:
variable that will be accessed
No�ce that it's
by default, yet it can s�ll be accessed
This is how we have been accessing the value stored in a variable, by just using
the variable name
value in
, is subs�tuted
for the variable name
is being accessed without using Dot Syntax or
Why do I even men�on using
at this �me? Later on when we get
into the State Machine, we will be using
. I want you to be aware of
what
is, a subs�tute for the current instance object of a class.
Now we start to just touch
on the real power of Dot Syntax, communica�ng with other
objects to access variable data and methods. We will now communicate with another
Component on the same GameObject, the
Main Camera
. Remember,
a�ached to the
Main Camera
already. The following diagram will explain how this is done:
current GameObject
To
access
item in
:
another
bold
Let's create another
script with a variable and a method, and a�ach it to the
Main Camera
then have
communicate with it:
In Unity, create another
C# Script
Make a
variable named
Assign some text to
Make a
method named
98 ]7.   Modify
to retrieve the
Component.
Modify
to retrieve the data in
Modify
to call the
Save your scripts.
Play
in Unity.
What just happened?
Here's
Component code retrieved a variable and called a method on
Component. Let's follow the code �ow with these two Components.
99 ]An analysis of the code shown in the previous code screenshot is as follows:
A variable
is declared to store a value of type
Component object will be created and stored in the variable
At the time of this writing, Unity was updating its documentation. The page
was not complete. The following screenshot is the old page; however, the
code is still valid.
Before you proceed further with the next sec�on, remove the
Component from the
Main Camera
. We are done with this script so there's
no sense in having any of its Components hanging around.
You just learned to access
Components on the same GameObject. Now it's �me to access
other Gameobjects, and their Components using Dot Syntax.
another GameObject
To
access the item in
:
bold
I want you to create one
script that will be a�ached to two GameObjects. The script will have
two methods that will cause the GameObjects to rotate le� and right. This will show you that
from a single script �le, two separate Component objects will be created in the memory. Each
Component object is a separate instance object with no absolutely knowledge of the other.
In your
, create two GameObjects,
Direc�onal Light
to the
so you can easily see the GameObjects.
Here's my
as an example:
Create a new C# Script and name it Spinner.
Code the script as shown in the following screenshot:
103 ]6.   A�ach the
script to the
Capsule
Modify
as shown in the following screenshot:
Save the
In Unity, click on
Play
104 ]What just happened?
Here's the output to the
Now press the le� and right arrow keys to make the Capsule spin, and the up and down
arrow keys to make the Cube spin.
You created one
script named
, then a�ached the script to two separate
GameObjects. When you click on
Play
, two separate
Component objects are
created in the computer memory. This is an example of how the
class is just
a blueprint, a descrip�on, of what each Component object created will be.
To access each
Component from the
Component, you need
to know about each GameObject that the
Component is a�ached to.
This code is just a simple demonstra�on to show how Dot Syntax works.
In real life, you may have each Component detect user input. On the
other hand, perhaps you may want a class dedicated to processing user
input. That's the neat thing about wri�ng code, there are a zillion ways to
accomplish a task.
An analysis of the code shown in the previous code screenshot is as follows:
variable of type
is declared
The value this will store is a reference to the
Capsule
A variable of type
is declared
The value this will store is a reference to a
Component object created from
105 ]Line 9: void Start()‹‹‹ ‹The Start() method is used to allow the two variables to be ini�alized
Remember, this method is called only once
method of the
class locates a GameObject in our
The reference to the
Capsule
GameObject is assigned to the variable
This is item 5 in the previous graphic and also on the previous code screenshot
This line was added just to show that the
Capsule
GameObject is in fact referenced
in the variable
106 ]Spinner (on the Capsule):
method called from the
Line 8 in the code block is executed
method on the
Component object is called which
causes
the Capsule to spin around the z-axis
No�ce though, that the variable named
is used in the Dot Syntax
statement instead of the
method shows 3 arguments being sent to the method.
In this example, the Capsule is rota�ng 60 degrees per second on the z-axis.
Code �ow now returns to the
Unity has a rather neat feature that allows us to assign GameObjects to variables without
wri�ng the code. It de�nitely has its uses, however, if it's not really necessary, I recommend
assigning GameObjects in code. Why?
Six months from now, when you are the stranger looking at your own code,
you may look at it and wonder why your code looks incomplete. It's your
game though, so you can create it anyway you please. I'm just saying, don't
go hog wild with drag-and-drop and then later wonder what it was you were
trying to accomplish.
Time for McPion – Prying drMg-Mnd-drop Po Mssign M GMmeONjecP
Let's change a few
lines of code in
to show how to
Capsule
GameObject to the variable
using drag-and-drop.
Either comment out line 11 using 2 forward slashes (
), or remove it.
like this:
Save the �le.
In Unity, select the
Main Camera
Drag the
Capsule
to the
Capsule GO
Inspector
following screenshot shows how this is done.
Play
What just happened?
Capsule
GameObject is now assigned to the
variable. We
didn't have to
write the code because Unity has done the assignment internally for us. Also, this doesn't
change
in any way.
v1. What is Dot Syntax, and what does it allow you to do?
v2. When an object is assigned to a variable, what is actually stored in the variable?
v3. Are there any limits to using Dot Syntax when trying to access variables and methods?
v4. What is another way to assign GameObjects to variables besides wri�ng code?
Summary
I hope you have discovered that Dot Syntax is actually a simple process for accessing other
objects. It's this ability to communicate between objects that make OOP so powerful. Data is
kept in objects, and methods are called on an object to get things done. Dot Syntax is just an
address to easily access data and methods on objects.
All right, we've covered the very basics of C# scrip�ng for Unity. Congratula�ons!
In the next chapter, I'm going to take you through a combina�on of Unity coding and general
C# coding to actually apply your new knowledge. We will start looking at a State Machine to
work with Unity. Yes, it's going to be a simple state machine to show the concepts. You've
just barely learned C# scrip�ng, so I'm going to ease you into some game crea�on which will
help you see how to apply the concepts that you've just learned. Besides, bet you're darn
sick and �red of constantly modifying, or completely changing
Creating the Gameplay is Just a Part
is usually the main thing everyone thinks of when first undertaking
the creation of a game. Build a scene, fill it with
GameObjects, and write the
scripts. After the game is well along in its development, a realization begins to
appear that there's more to a game than just playing it. Putting a game on the
market means it has to include things such as beginning title screen, the game
options, or a player settings menu. Also, what happens when the user wins the
game, or loses the game? It's one thing to write the code for GameObjects, but
what about the code to add on all the other parts that come before and after
In this chapter, we'll begin work on a C# State Machine, one possible solution
for providing the necessary base code to easily incorporate the non-playing
In this chapter we will discuss the following topics:
How a State Machine helps in making a game easier
A logic overview of the di�erent States
The base code for crea�ng the State Machine
So let's start to glue things together.
112 ]Applying your new coding skills to a State MachineYou learned the
fundamentals of C# coding in the
previous six chapters which were used for
crea�ng Components. You will use the same coding fundamentals to create a State Machine.
You have learned in
Chapter 6
Using Dot Syntax for Object Communica�on
, that an object
created from a class is called an instance
of the class. In Unity, an object created from a class
is called a Component. These terms may be di�erent but they mean exactly the same; an
object is created as de�ned by a class.
However, there is a
di�erence in the way the tradi�onal C#
environment of the State
Machine gets an instance object created, and the way Unity gets a component object
created. The di�erence is as follows:
A class we write for Unity has to be a�ached to a GameObject.
A class we write for the State Machine is not a�ached to a GameObject.
Unity hides the code that is necessary to create an object. Unity knows to create
the object because it's a�ached to a GameObject.
For the State Machine, we have to write the code that is necessary to create
Have no fear! It's very similar to the code in
Chapter 5
we used to create a
State Machine lies in its simplicity, and you are already familiar with the
concept. You probably spent at least the �rst 14 years, maybe more, of your life living in a
State Machine environment; you just didn't know that it was a State Machine at the �me.
As a child, your parents were always making you take a bath, go to school, do your
homework, go to sleep, and whatever else you always had to do. When you were in school,
you were in the school State. Were you allowed to do anything else? While sleeping, you
were in your sleep State. Were you allowed to do anything else? How about the do your
homework State?
The idea of being in a certain State is that you can only do what's allowed in that par�cular
State, but you do it very well. When you put a computer program in a par�cular State, it
will stay in that State doing only what it's supposed to do un�l it's told to change to another
State. This is exactly what you want to do in Unity, put your game into a par�cular State to
perform the speci�c behaviors you desire.
113 ]Bene�Ps of Ny using M SPMPe MMcOineThe following are
the bene�ts of
using a State Machine:
A very clean layout or map of the game control
Very clear points to add game func�onality or features
Cleaner, smaller, and very speci�c code in each State
It is easy to extend game logic by simply adding another State
The primary bene�t of using a State Machine is for code organiza�on. Typically, a game
may start o� being simple and following the code �ow is easy. Unfortunately, games don't
seem to stay simple. Features are added, code has to be changed with
statement a�er
statement added to control the game logic. It turns into a nightmare just trying to to
keep track of where a speci�c pieces of code may be located. You'd probably add more
Components to GameObjects to try to make the logic sensible. Even worse would be the use
of global variables to pass data around to Components. Then you have to keep track of which
Components access which global variables and hope the data stored is what you think it is at
the �me you access it. Trying to follow the logic ends up being like a bowl of spaghe�.
Doesn't it make sense to use the capabili�es of C# to create speci�c State objects to keep
game logic well organized, instead of a�aching Components to GameObjects �lled with the
spaghe� code?
The following diagram is the basic concept of a State Machine
for controlling a Unity project:
Unity calls the
method every frame
script is the heart of the State Machine, a Component that has
method
The code block of
delegates (transfers) control to the State that is ac�ve
States are regular C# instance objects and not GameObject Components
The ac�ve State determines what is displayed, and therefore, is the logic controller
of your game
114 ]‹‹‹ ‹The ac�ve State decides when and which State will be ac�ve next:
the game Scene and logic
the game Scene and logic
the game Scene and logic
the game Scene and logic
gives it control
The heart of
the State Machine is the
script. This is a Unity class, so it
inherits from the
class. The script is a�ached to a GameObject to
become a Component. The following are the three core
features that the
script handles:
Delega�ng game control to a State
Switching to another State when called to do so
Keeping track of the ac�ve State
script is
like any other Unity script. It is
a�ached to a GameObject
and becomes a
Component object. The
script uses the
method
to pass the game control to the ac�ve State as shown in the following diagram:
The following diagram does not show complete code
statements.
Active State
void
update()
{
activeState.StateUpdate();
}
StateUpdate()
{
Game code goes here
}
The game control code that's usually in an
method is instead delegated to
method
object. So every �me Unity calls the
method on the
Component, the
method is
called on the currently ac�ve State object.
Please understand this principle of delega�ng, or transferring, responsibility
from the
method of the
script to the
method on the current ac�ve State. Believe it or not,
that li�le bit of code is the primary driver of the State Machine's opera�on.
No ma�er how many States you may use to control your game, always remember the
following points:
Every State will have the
method, guaranteed
The code block logic will be di�erent for each
method on every
State, depending on what you want each State to accomplish
Only one State is ac�ve at any �me
Each State determines
why and when to switch to another State. You could have an almost
unlimited number of reasons to switch to another State, such as losing the game, winning
the game, touching some special GameObject, solving a puzzle, or the user pressing a
bu�on. No ma�er what the reason is, it's the code in the ac�ve State that will trigger the
switch to another State.
116 ]The SwitchState() method on the
script is called to accomplish this.
The following diagram does not show complete code
statements.
Active State
void
SwitchState(newState)
{
activeState = newState;
}
When the ac�ve State has been determined, it is �me to switch to another State; the
method on the
is called.
takes an
argument of the new State, which will become ac�ve next.
This newly created
State is then assigned to the
variable. Why?
In order for a State to control a game,
needs to know about it. A reference
of the ac�ve State
object is stored in the
variable.
So when Unity calls
script, control is passed to the newly
created State that's stored in
by calling its
method. The
State Machine cycle of changing to a new State is complete.
Review the following steps:
The ac�ve State determines when it's �me to switch to a new State.
A new State object is created and passed to the
script using
method.
This new State object is assigned to the
variable.
is called on
method
delegates control to the
method on the new State.
Now go
back to step 1.
117 ]Creating Components objects and C# objectsSo far in this book, you've
been taught the basics of wri�ng code to create Components for
GameObjects. Incorpora�ng a State Machine into Unity means I have to take you just a li�le
further into the normal C# programming environment.
This will help your game coding in two ways:
You will understand what Unity is doing behind the scenes when it creates
Component objects in memory
Making use of a C# interface will help with the game control logic
Unity creates Components behind the scenes
You already know
that a Unity script is really just a �le on your hard drive that de�nes a class.
A�aching this script to a GameObject allows Unity to create a Component object in memory
when you click on
Play
Unity hides this process of crea�ng a Component object from your view. In my opinion,
making things simple by automa�ng processes is great because it saves �me; however,
it doesn't help you understand how to code.
There are third party products available that try to totally automate the code wri�ng. Once
again, this is a good thing but if you �nd you need to tweak or modify anything to get the
exact behavior you demand, you have to get your hands dirty at some point and actually
modify or write the code you need.
Well, guess what? If you don't understand how a code works, you're stuck. Learning some
C# basic programming skills doesn't require a PhD in Rocket Science. If you truly want to be
comfortable using Unity, knowing the basics of C# is required. You don't have to know all
kinds of advanced C# coding skills to write scripts.
Look back at the material you learned in the �rst six chapters of this book. There wasn't
anything so earth-sha�eringly complicated that made you throw your hands in the air and
give up. Sure, there were a bunch of words you had to learn, but everything you learned
was just basic, logical steps.
Here's another new word,
instan�ate
Not to worry, it's
just a word that means create an object from a class. I've been saying
create an object throughout this book. Now you have a word for it.
This is what Unity
the scenes when a Component is created. The script we've
class. When you clicked on
Play
, Unity instan�ated
to create a
object which was a Component object of
Main Camera
We're going to leave
behind and start using
State Machine.
Delete
from your
folder in Unity.
We are going
to
create the
script and the
code so that we can
instan�ate
to make an instance of
help of the next screenshot, perform the following steps:
Project
window, create a
C# Script
folder.
Name the script
to open it in MonoDevelop.
In the MonoDevelop
window, right-click on the
folder and select
New Folder
Name the folder
Right-click on the
folder and select
New File
New File
window, select
General
Empty Class
�eld at the bo�om, enter
New
bu�on to create the
The following screenshot is the
window of MonoDevelop:
119 ]With the BeginState class �le open in MonoDevelop, make the changes as shown in the
next screenshot:
Change line 1 to
Change line 3 to
in MonoDevelop, and make the following changes:
120 ]The StateManager class �le should look like the
following
screenshot:
What just happened?
In the Unity script,
, we are instan�a�ng the
class and storing a
reference of (poin�ng to in memory) this new
variable
This basic process of crea�ng objects will be used in the State Machine to switch
from one State to another State. Instan�a�ng classes is also what Unity is doing
when it creates Components.
As an example, in the
Scrip�ng Reference
, search for and select
. You will
see a variable listed named
. When you click on
Play
, Unity instan�ates the
class and stores a reference to the
Components object in the
variable.
that if you need to
the data for a GameObject's
Components, you can simply use the
variable instead of having to use the
As a li�le refresher,
is the name of the variable that will store a reference to the
object created when you click on
Play
This is exactly the same thing you are doing with the �les you just created. The
is the name of the variable that will store a
reference to the to the
object created when you click on
Play
We are going to instan�ate
class to create an instance object in the
memory. This will demonstrate how objects are created. Before we can do this, we �rst need
to a�ach the
script to a GameObject. To do so, perform the following steps:
A�ach the
script to the
Main Camera
Play
to show the results in the
Console
as shown in the following screenshot:
What just happened?
method
class is a special method known as
a constructor. It serves the same purpose as the
method or the
method in a Unity script to ini�alize any member variables in the instance object created.
A constructor method does not have a return type, not
even
I didn't have any variables to ini�alize, so I just sent a message to the
You could see that this method was actually called. See the �rst step in the
previous screenshot.
The second step in the previous screenshot shows that the value stored in
variable is a reference to an instance object of the
The following
is the code analysis on various classes:
An analysis of the code shown in the preceding code screenshot is as follows:
is a variable that can store a reference to an object of type
variable is private because you don't want any external code to
change the stored value
122 ]Line 10: activeState = new BeginState();‹‹‹ ‹The new operator is how you create an instance of a class
This means an instance of
has been created in memory
Code �ow now jumps over to line 7 in the
An analysis of the code shown in the preceding code screenshot is as follows:On
This is a constructor to ini�alize any member variables in the newly created
instance of the
A constructor method name is the same as the class name
This line is just sending a text message to the Unity
to show that the
constructor was called when the instance object was created
This method is now �nished and code �ow returns back to
An analysis of the code shown in the preceding code screenshot is as follows:On
A reference to the
instance object is assigned to the variable
This message
is sent to the Unity
to show you that
does reference an instance object of the
Specifying M �le's locMPion RiPO M nMmespMce declMrMPion
Earlier you
changed line
. What is
If you look up namespace on the Internet, you might be overwhelmed with explana�ons.
For wri�ng classes in Unity, I'll boil it down to this:
declares where a class �le is located in the Unity
Project
folder structure.
123 ]For coding in the Unity environment, that's really all you need to know.
folder, which is a subfolder of the
folder, which
in turn is a subfolder of the
If you move the �le to a di�erent folder, you will have to
change the
as well.
Look at
. You
124
Every �me you create a script, you get to control whether a variable is private or public.
If you make it public, you have stated that the variable is an interface on that class.
It even appears in the
Inspector
panel, which is another interface.
How about methods? If it's public, then it's an interface point that can be used from
TOe SPMPe MMcOine Mnd POe inPerfMce guMrMnPee
All States have to
incorporate
par�cular methods that the
class can call.
Therefore, the States have to guarantee that these methods are implemented, otherwise
the State Machine won't work.
Well, since you write the code for your classes, can't you just remember and make sure
these required methods are implemented on each State? Sure, that's possible, but it's not
a guarantee, is it? Suppose your game has ten possible States. There's just too much room
for spelling mistakes, or just plain forge�ng to implement the required methods.
C# does have a way to
guarantee that the required methods are
implemented in each State
by using a C#
. I know, I've been using the general word interface a lot here, but
that's what it's called, an
Time for McPion – implemenPing Mn inPerfMce
We're going to create a
and implement it in
, but incorrectly to
see some errors. Then we'll implement the interface correctly. Perform the following steps:
In the MonoDevelop
window, right-click on the
folder and select
New Folder
Name the folder
Right-click on the
folder and select
New File
New File
window, select
General
Empty Interface
In the Name �eld at the bo�om, enter
IStateBase
New
bu�on to create the �le.
125 ]In the MonoDevelop
window, your �le structure will now look like the
following screenshot:
Now edit
�le as follows:
Remove lines 1 and 2. As a result,
will move up to line 1.
Modify line 1 to:
Now we're going to
have the
class partly implemen�ng the
interface so that we can see how using an
guarantees our State classes meet
the minimum requirements for the State Machine.
Now edit the
class as shown in the following steps:
126 ]We have now partly implemented the
interface.
now look like the following screenshot:
Save your �les.
Switch back to Unity and no�ce that you get two errors in the
We were just told by
Unity that we messed up. There are two errors informing us that
did not properly implement the two methods required by the
interface:
This is exactly what we want the Unity to tell us. On line 6, we said
we were going to use an
to guarantee that all methods
speci�ed in the interface are included in our State classes. We didn't do
it, so Unity let us know.
Now let's almost correct the code in the
Add in the two methods as shown in the following screenshot. No�ce that I'm
method as
Save the �le.
No�ce that Unity s�ll let's us know that we're messing up.
Correct the spelling (remove the extra
from
Save the �le.
Play
in Unity to verify that your code now works correctly.
What just happened?
output should be exactly as it was before we created and implemented the
interface. Even though more methods were added to
, there's
nothing in the code blocks to execute, nor did we change
to call the
methods. Our focus was to show how to implement an interface, and how it guarantees
that the interface methods for a class are included correctly.
HMve M go Oero – Mdding MnoPOer mePOod Po POe inPerfMce
In a later chapter, we will be adding a third method to
named
. You may add it now if you wish. This will require you
to implement the
method
in all States we create.
v1. What is the main reason to incorporate a State Machine into a game?
v2. Since State classes aren't a�ached to GameObjects, how does the code in a State
get executed?
v3. How many States are allowed in a State Machine?
v4. What should you use to guarantee that all States have the required code for the State
Machine to operate properly?
Summary
We learned why a State Machine is a great way to glue the di�erent parts of a game
together, each part having it's own State of control. Then we learned a basic overview of the
logic of switching States. We even took a brief glimpse into how Unity creates Components
to help your understanding of code logic. Finally, we covered a way to guarantee that each
State in a State Machine contains the required methods to make the State Machine work, by
using a C# interface.
There are more great bene�ts for using a C# interface besides the programming interface
it provides. In the next chapter, we get into the details of the State Machine and how the
interface can work for us even more.
It's time to code the State Machine so we can test its operation. We need
to write the code for four initial States, the StateManager, and use the
interface. We will first have the State Machine work with three
States and then show how easy it is to add in the fourth State.
Your Unity project may need more than four States. After you see how easy it is
to add a State and how clean, simple, and organized it makes your code, your
imagination may run wild on how you could make use of these States.
Object Oriented Programming (OOP) is to create objects,
(little packages of data) and action code (methods). In Unity, these objects are
used for controlling actions in your Unity project, and they communicate with
each other as well. A State Machine is simply a design choice for these objects
that allows you to better organize and maintain your code.
The topics covered for the State Machine are as follows:
Crea�ng State classes
The StateManager controller
The ac�ve State and Unity's Scene
Well then, let's get stated...
As we create each State, you'll no�ce that each one is iden�cal in structure. Again,
this structure, this class interface, is
guaranteed to be iden�cal because implemen�ng
makes it a requirement that certain methods are included in each State.
When we modify the
, you'll see that it guarantees each State will implement
interface as a requirement for being a part of the State Machine.
We already have
started from the previous chapter, but it needs some
modi�ca�on to be func�onal in the State Machine. So let's modify
�rst, and
then create the other three States:
Time for McPion – modifying BeginSPMPe Mnd Mdd POree more
Once we modify
we'll essen�ally use it as a sort of template for crea�ng all
the other States, with just a few minor di�erences.
I will explain code �ow once we have the State Machine opera�ng.
Using the next screenshot of
, make the following changes:
Modify line 10:
131 ]Follow these
next steps three �mes to create the other State classes:
window of MonoDevelop, perform the following steps:
Right-click on the
folder, and select
New File
New File
window, navigate to
General
Empty Class
At the bo�om of the window, enter the class name.
New
bu�on.
In each of the three new �les, make them almost iden�cal to the code of
except
for the class name, the constructor method name, and the text in the
statement.
Line 6 on each respec�ve class �le will be as follows:
Line 10 on each respec�ve class �le will be as follows:
13 on each respec�ve class �le will be as follows:
statement is not a requirement in these State classes.
They are only there temporarily for tes�ng. They will be removed later.
Each State is responsible for determining why and when to switch to another State. Since
there is no game code at this point, we need to manually switch States to test the State
Machine. We will do this by Unity detec�ng when we press the Space bar key.
132 ]Add the following
statements to the
method code block (line 18 in the
previous screenshot) for each State:
variable needs to be able to store all of the State types. Right now it can
only store a reference to a
type of object. This looks like a huge problem! What
? What if we had 50 di�erent
States that needed to be referenced in
The following diagram is our dilemma:
BeginState
object
PlayState
object
W
onState
object
L
ostState
object
PlayState
class
W
onState
class
L
ostState
activeState;
object
only
The variable
is
activeState
of type
BeingState
Therefore, this variable
can contain
activeState
object
BeginState
It cannot contain any other
type of object, such as
,,
or
PlayState
W
onState
L
ostState
134 ]SPudying Mn exMmple of inOeriPMnceLet's look at this issue using objects we all use all the �me.
How about a Potato?
Let's also imagine we have a Potato bag. Now to connect these real
objects into the scrip�ng world, the following is a simple declared variable:
So we have a variable named
. The type of object it can store is a
. Saying this
in another way:
I have a Potato bag, and the only thing I can put in it is a potato
shown in the following diagram:
P
otato
Steak
class
L
We're not allowed to put a Steak, a Le�uce, or a Donut object into a Potato bag.
This is exactly the same issue we have with our
variable that is declared to
only store one type of object, a
object. We can put a
135 ]So what do we do now?
Let's get back to the Potato example. Instead of using a very speci�c Potato bag, how about
the bag a bit more general, like a Food bag? Can we put a Potato in a Food bag? Is a
Potato a Food? Well, we eat it, so it is a food. How about a Steak? Is that a food? Sure it is.
:
P
otato
F
ood
:
Steak
F
ood
class
:
L
Look at each class declara�on right below each Food object. Each class inherits proper�es
from the
class. Now that we're also classifying each object in the more general class
, we can now declare that the variable
can hold a type of
That's great. So, we can do something similar with our classes as well, such as create a more
general
class for the State Machine, and then modify each State class to inherit
from
, and the problem is solved. Yes, we could do that and make the State
work. However, inheritance does have some limita�ons in a State Machine and they
are as follows:
If we use inheritance, every method that's inherited will be iden�cal, which is not
what we want. The State methods need to have a code block speci�c to its needs.
Using an inherited method is op�onal which is not what need what. We want to
guarantee that the methods will be used.
If we chose not to use an inherited method, then why bother crea�ng the class in
the �rst place?
136 ]‹‹‹ ‹Also, if we created a State system using inheritance, and later wished we could
inherit from more than one class, we're out of luck.
A C# class can only inherit from one class.
The ques�on is what to do now?
EnPer POe HSPMPeBMse inPerfMce MgMin
We don't have
to create another class for the State classes to inherit and get the State
Machine to work.
An interface behaves just like inheritance, plus a class can
implement more than one interface.
Each of our
States is already implemen�ng the
interface to guarantee the
methods are included. Now, since
acts like it's being inherited, it means each
of our States can be treated as if they're an
What we'll have a�er we modify
is shown in the following diagram:
is
activeState
of type
IStateBase
Therefore, this variable
can contain
activeState
any object that implements
the
IStateBase
interface
The classes
,
BeginState
,,
and
PlayState
W
onState
implement the
L
ostState
IStateBase
interface
Therefore, any objects
created from these
IStateBase
IStateBase
object
activeState;
BeginState
IStateBase
object
PlayState
object
W
onState
object
L
ostState
object
class
PlayState
IStateBase
class
W
onState
IStateBase
class
L
ostState
IStateBase
137
interface
is providing a
double guarantee that:
The State objects will have the required methods that
to access
variable, of type
, requires all States to implement
Time for McPion – modify SPMPeMMnMger
Edit the
class to use the
interface. This allows the
variable to store all of the State class objects. Also add the code that
does the switching to the next State:
Modify
as shown in the next screenshot.
Remove the
statement.
Save all �les.
Play
Now press the Space bar key to cycle through the States.
138 ]What just happened?
The following is the output to the
as you repeatedly press the Space bar key:
The State Machine starts with
being ac�ve. Pressing the Space bar key makes
the ac�ve State. Pressing the Space bar again makes
the ac�ve State,
and then pressing
the Space bar key once more makes
ac�ve again.
We now have a working State Machine. For the bene�ts a State Machine provides, there isn't
much code involved to changing States.
Let us follow the code �ow for switching States:
There are no States
created as of yet
script is a Unity script, therefore Unity instan�ates (creates)
Component object
variable will store a reference to a State which is an
variable currently has a value of null, meaning there is
no reference to a State object stored yet
Unity then calls the
method, execu�ng line 11
keyword instan�ates the
constructor method is called, and passes the argument
to the
constructor
139 ]‹‹‹ ‹The this keyword is a reference to this object, which is the
Component object
is receiving a reference to the
object at line 11
This is the constructor for ini�alizing member variables
The parameter variable
is assigned the reference of the
reference that is stored in
, is assigned to the
member variable
that was declared on line 8
The variable
stores a
type of object
Every �me a new State is created,
stores a reference of the
class, because each State needs to be able to call the
method on
This simply sends a text message to the Unity
This is needed temporarily so we can see the States changing when we press the
Space bar key
The code block is now �nished
Code �ow now jumps back to the place that had called this
constructor method, which was
object has been created and ini�alized
A reference of the
object is now assigned to the member
variable
At this point,
is now the ac�ve State.
140 ]Line 14: void Update()‹‹‹ ‹This method is called every frame by Unity to execute its code block
statement says that if the value in
is not equal to null,
then execute
to see if the variable
is storing a reference to a
State object
If it isn't, the value stored will be null, like it was when we �rst clicked on
Play
is now storing a reference to
statement
Using Dot Syntax, the
() method on
is called
every frame
The code �ow now jumps to line 16 of
This method is called every frame by the
There is no game to control yet, nor any game generated events
Therefore, we are simply checking for a press of the Space bar key to
change to another State
141
Similar to the
constructor method, the
constructor
method takes a parameter of a reference to
, which is stored in the
member variable
Code �ow now jumps to line 10 of
to ini�alize it's member variables
The code flow logic for line 10 of
The argument
is now a reference to the new
object just created
reference that is actually passed to the
method on
Code �ow now jumps to
The parameter takes the
object reference and assigns it to the
variable
This variable stores an
Remember, all States implement the
interface
reference stored in
is now assigned to
At this point,
is now the active State.
I did a lot of explaining,
but there were just the following basic things that took place a�er
Play
object instan�ated a
object and stored its
reference in
object waited for us to press the Space bar key to switch States.
object instan�ated a
object and told
to store the
class reference in
Note that steps 2 and 3 just repeat for switching to any State, no ma�er how many you have.
You've probably no�ced
we haven't used
. Let's see how easy it is to include
another State.
Time for McPion – modifying PlMySPMPe Po Mdd MnoPOer SPMPe
We s�ll don't have any
game logic to call for State switching, so we'll just simulate being killed
in the game by detec�ng when the
Return
Enter
key is pressed. Add another
statement in
the
() method of
, as shown in the following screenshot:
What just happened?
That's it. That's all it takes to add another State. Simply call the
method to
instan�ate any State class you wish.
The following is the
output when you press
Return
Enter
What happens
if you press the
Return
Enter
key while in any of the other States? Nothing,
of course. There's no code for the
Return
Enter
key
in the other States.
This maybe a simple example, but it demonstrates how each State
has its own controlling game code.
interface requires that each State class have the
method. The
method will also
be called from the
. It's �me to connect this
method with the
code.
The
class needs
to have Unity's
method. Just the way the
method transfers control to the
method on the ac�ve State, the
method transfers control to the
method on the ac�ve State as well.
Active State
ShowIt()
{
GUI code goes here
}
onGUI()
{
activeState.ShowIt();
}
method
to
as shown in the following screenshot. Begin
the method on line 22:
What just happened?
Unity calls the
method at least once per frame, but it could also be several �mes
per frame. This means that the
method on the ac�ve State will be also called for
displaying graphics, text, and bu�ons.
Our State Machine is presently changing States in the only
we've created, which is
. The four States we created have the names
However, there could be a poten�al issue.
Let's say you wanted
to display a cool fullscreen graphic. The issue is that
behind that graphic, your game would be ac�ve. You won't be able to see the ac�on because
of the fullscreen graphic blocking your view. This is not an ideal situa�on.
GameObject to
Component to the
GameObject so it will fall to the
Direc�onal Light
to the
panel if there isn't one already.
Then we'll add a GUI bu�on
to switch to the
object. To do so, perform the following steps:
In the menu, navigate to
Create Other
Inspector
panel, make sure the Posi�on is
for
In the menu, navigate to
Create Other
Set the values in the
Inspector
panel as shown in the next screenshot.
Hierarchy
In the menu, navigate to
Component
Physics
In the menu, navigate to
Create Other
Direc�onal Light
Add the following code to the code block of the
method of
145 ]What just happened?
We now have a li�le bit
of ac�on in the Scene. When you click on
Play
, the following
screenshot will be shown:
falls to the ground,
, as shown in the following screenshot:
your game had many things moving around, and instead of a bu�on, you had a
fullscreen graphic. You will not see any of that movement, nor will
you really want all that
ac�on taking place before you switch to the
There is a li�le
trick you can use to stop all the game ac�vity while in
variable, which you can set to slow down your game or stop
it completely. It's similar to a pause feature.
we're going to set
to zero to pause the
. Then before
switching to
, we'll set it back to normal speed. Perform the following steps:
Modify
in two places as shown in the next screenshot.
Save the �le.
What just happened?
An analysis of the code shown in the preceding screenshot is as follows: On the
This line makes �me in the game to stop
This sets the game speed back to normal when switching to
Play
again.
Now the
GameObject is suspended in air. Click on the
Press to Play
bu�on and everything is back to normal and you're in
No�ce how the bu�on disappears when you change States. Once again, this shows the beauty
of the State Machine. You don't have to use a bunch of
statements to make things appear or
disappear. Each State determines the control you want and what shows on the screen.
147
It's great being able to stop �me like that, but what if you wanted
to be ac�ve
for only a few seconds and then automa�cally change to
? By se�ng
to zero,
any �mers are now frozen in �me.
Unity has a �mer that runs, no ma�er what. It's a variable in the
class called
Play
is clicked, this variable is constantly updated with the
running �me of the game. We can use this to create a simple �mer in
to make
it switch to
I've modi�ed
quite a bit just for the �mer. There are now three examples of
ways to switch to
. Plus, there's a �mer countdown displayed in the upper right
corner. I also put code that I had to write more than once into a new
method.
Edit
as shown in the following screenshot.
Save and play in Unity.
148 ]What just happened?
I'm not going
to walk you through the State switching code, I already did that previously.
An analysis of the code shown in the preceding screenshot is as follows: On the
For lines 9, 10, and 11:
Three member variables are declared for use in the countdown �mer
These will be explained later when they are used in code
The reason they are declared here as member variables is that they need to be used
in more than one method
Remember
the variable scope, variables are only visible within the code block
they reside in
Scripting Reference
has a good description of
which is exactly the reason we are using it.
The current elapsed �me is retrieved from
with the value in the
variable
variable was declared on line 11 with a value of 8
seconds, which is the length of �me
will be ac�ve before switching
to
The result of the addi�on is assigned to the variable
149 ]Line 17: Time.timeScale = 0;‹‹‹ ‹Assigning 0 to the
variable causes �me in the game to stands�ll, thus
pausing the game
Both the lines 16 and 17 are executed in the
constructor
because it's only called once each time an instance object of
is created. We want to pause the game at the instant
is created. We also want to set the timer as well.
The variable
is declared and assigned the current elapsed �me
So we have
in front of each variable. The two variables are of type
, while countdown is of type
. I want it to be of type
used later in line 38. The
type takes the
value, strips off the
decimal part of the number, and leaves just an integer. A
is being
cast (changed) to an
150 ]Line 27: Switch();‹‹‹ ‹The code that used to be here was moved to the new
method on line 41
This line calls the
method
The code �ow now jumps to line 43
This line assigns the value
to
Now the �me in the game is back to normal
Remember, we had set it to
This is the same switching code we always had to switch to
, it's just in
method now
Code �ow now returns to line 27 where
was called
The code block is �nished
The following
is the code �ow of
Scrip�ng Reference
It returns a Boolean (
) of true when clicked
Therefore, we use an
statement to detect when it's clicked
method has the following two parameters:
object (rectangle) is created which specifies its position on the
screen and its size
text that will be on the button
This line calls the
method on line 41
method creates a visible rectangle box in the
to display the �mer
coun�ng down
151
Because I wanted the box on the right side of the screen no ma�er what resolu�on
the screen may be,
provides the pixel posi�on of the right side of
. Then I moved
pixels to the le� of the right edge of the
mean: from the last pixel on the right, come back 60 pixels to the le�, and
that's where to start drawing the rectangle box.
method takes an integer value stored in
and converts it to a
value.
It converts it to the string value because the second parameter of the
method requires a
type of value.
Considering how much is going on in the
, and that there are three ways to change to
, there really isn't very much code in
When you know the syntax, how to use variables and methods, and the concept of working
with objects, coding is actually quite simple to learn because you're doing the same types of
thing over and over. The most di�cult part of coding is trying to discover all the features that
Unity provides in the
Scrip�ng Reference
, and how they work.
You could get to know C# to the point where you dream in code, but then you have to apply
that coding knowledge to Unity. So you look in the
Scrip�ng Reference
and think what is
vuaternion
? What takes �me is doing the research, and not necessarily
wri�ng the code.
Assuming that
will appear when the game starts and again a�er you lose,
change
to switch to
instead of star�ng over with
Hint: you have to change only one word in the
The neat thing about wri�ng code is that there are a zillion ways to do something. Put 100
code writers in a room and tell them to make a countdown �mer. You'll probably get 100
di�erent ways to do it, and they'll all work.
So far, the State Machine
is working with one
to setup game control. Well, suppose we
wanted to use another, or several
, or perhaps we don't want to use
. Of course, some changes will need to be made to work with more than one
152
We're going to create a new
for
. As a result, we don't want the
object to be a Component of the
Main Camera
anymore. We'll add
to
another GameObject in the new
. In order to do so, perform
the following steps:
Remove the
Component from the
Main Camera
Make a new
by selec�ng on the menu
New Scene
In the menu, navigate to
Create Empty
Rename the
to
GameManager
StateManager
script to the
GameManager
In the menu, navigate to
Save Scene as...
Save the Scene as
folder.
Play
to verify if the State Machine is working as before.
At this point, a�er clicking on
Play
, you will see the
Press to Play
bu�on and the countdown
�mer in your Scene.
Scenes to the
Build Se�ngs
as shown in the following steps:
In the menu, navigate to
Build Se�ngs...
Build Se�ngs
window, click on the
Add Current
bu�on to add the
to the
Drag
into the
Build Se�ngs
window.
Edit
to delete line 17,
153 ]What just happened?
By using a separate
is ac�ve, there's no longer any reason to
pause the game.
In the upper right corner of
Build Se�ngs,
you can see that
is index
is index
. If you build this project, index
will be loaded automa�cally. It doesn't
work
this way in the Editor. Whatever
is loaded runs when you click on
Play
We have two
issues when using more than one
but both can be easily remedied:
Every GameObject in the current
gets destroyed when another
When the game starts in
GameManager
is created with the
Component and
being ac�ve. When
switches to
GameManager
be destroyed.
Every �me
is reloaded, another
GameManager
Component is created.
That simply isn't going to work very well. Throughout the game there needs to be
GameManager
We want the �rst
GameManager
Component to always be available.
A�er all, it's the controller for the whole project. To prevent
GameManager
from being
destroyed when switching from
to
, Unity provides a method called
We will add this in a moment, but the second issue has to be dealt with at the same �me.
In our State Machine, we have
switching back to
. The issue is that
is reloaded, another
GameManager
GameObject will be created. We
don't want another one. We just want the �rst one we created when we �rst clicked on
Play
This is easily remedied as well by detec�ng that our �rst
GameManager
already exist and
immediately destroying any new ones that are created.
In the code block of the
method, we're going to check if the
GameManager
already exists. If it doesn't, we'll save it to a variable and tell Unity not to
destroy it when any other
level is loaded. If it does already exist, we'll tell Unity
to destroy any new
GameManager
GameObjects created.
Insert the new code as shown in the following steps:
Add a new
variable on line 9.
method at lines 11 through 22 as shown in the
following screenshot:
What just happened?
An analysis of the code shown in the preceding screenshot is as follows:On the
This variable named
stores a
a reference to the
object in the memory
variable
This means, that in this example, each instance of the
Component object that's created will share and see the same value
it can't be changed from outside the
155 ]Line 11: void Awake()‹‹‹ ‹Unity calls the
method once a�er all objects in the game are loaded into
memory, and before the game actually plays
statement is checking whether the
already stores a reference
to a
Component object in the memory
If the value is equal to
, meaning no reference is stored, the
code block
is executed
If the value is not
, meaning there is already a reference to a
Component in the memory, the
code block is executed
Since there's no
Component reference stored,
, which stores a
reference to this
, is assigned to
This will be the case when the game has just started and the
Component is created for the �rst �me
This method tells Unity to not destroy the
GameManager
Component is a�ached to when changing to another
level
is reloaded, another
GameManager
GameObject is created
is not null, this second instance needs to be destroyed so that
GameManager
exists
method destroys the second copy that
was just created
Now let's write
the code that will change from
to
, and back to
We'll add a single line of code in
to change Scenes.
into the
method on line 42 as shown in the following screenshot:
into the
method on line 20 as shown in the following screenshot:
If earlier in this chapter you changed
to switch to
instead of
star�ng over with
, we're ready to test our State Machine again. If you
didn't, the following are the changes you need to make to
157
Save all your changes.
Have
loaded and showing in Unity.
Play
What just happened?
You should now be
changing Scenes as you go from
to
. To get back
to
, you have to �rst switch to
Q1. The State classes implement the
interface guaranteeing certain methods
are included. What is the other very important feature that the interface provides for the
State Machine?
Q2. Each State has to have the
methods. What calls
these methods?
v3. What normally happens to GameObjects when changing to another Scene?
v4. Is this sentence true or false? Once a State Machine is setup, it can't be changed.
Verifying POe code of your clMsses
Just in case
you've had any di�culty because of constantly edi�ng your class �les, the
following are the screenshots of
as they currently stand.
158 ]The following is the screenshot of the
159 ]The following is
the screenshot of the
160 ]The following
is the screenshot of the
The following is the screenshot of the
161 ] The following
is the screenshot of the
Summary
This chapter was full of op�ons and details about using the State Machine. We started by
crea�ng four States and se�ng up the
class to be the controller with the
help of a C# interface. We learned how to load Scenes when switching States, and keep
GameObjects from being destroyed in the process. We also covered using �mers and how
to pause a Scene.
For such simple code, the State Machine o�ers a tremendous amount of control and
�exibility in organizing your game code. Let's start o� the next chapter by using this
State Machine to actually control a few GameObjects and change States.
164 ]Easing into Unity's scripting documentation
It's great that Unity has so many classes in the Scrip�ng Reference for us to use in a Unity
project. Yet, for a beginner
to scrip�ng, even the amount of features available in the Scrip�ng
Reference can be overwhelming.
The good news is the Scrip�ng Reference is exactly what the name implies. It's a reference.
It's not meant to
be a document you have to totally understand before you can begin wri�ng
scripts. A reference is a document you search when you need to know how to write the code
to perform a speci�c task.
That's great, right? Sure it is, sort of. As a beginner, how do you know what to search for?
This reminds me of school. Ask the teacher how to spell a word and the teacher always
responded with "Look it up in the dic�onary." Ok, but how do you �nd out how to spell
a word in a dic�onary if you don't know how to spell it to �nd it? I always thought the
teacher's answer was rather lame and a waste of energy. I didn't want a de�ni�on, just
how to spell it.
Let's assume that you wanted to
between two vectors. Say what? Now seriously, how in
the world would a beginner know words like this in the �rst place? What the heck is a "lerp"?
Would you know to search for that word in the Scrip�ng Reference?
Obviously, most beginners wouldn't know a great deal of the terms, classes, variables, and
methods available in Unity. This book is about teaching you the basics of C# so that you can
understand code examples presented in the Scrip�ng Reference, and be able to implement
similar code in your Unity projects.
Right now, you are at the beginning of your coding educa�on. Learning the fundamentals of
C# coding is the easy part, it's like learning how to read and write a sentence.
Now that you can read the C# code examples in the Scrip�ng Reference, it's �me to establish
a logical approach to access the informa�on it contains. Yes, reading the Unity Manual and at
least glancing through the Reference Manual is a requirement. You may understand C#, but
now you also have to know how to access the power in Unity, and C# is your key to unlocking
that power. The Scrip�ng Reference is only a good reference if you have a basic understanding
of what you are looking for, and that knowledge comes from reading the manuals.
The easiest way to view Unity's documenta�on is to click on
in Unity's menu bar.
165 ]ReMding POe UniPy Reference MMnuMl �rsP
This manual provides a general overview of the main features (classes) you will be accessing
while wri�ng your code. A lot of the terminology you need to know is here. At a minimum,
read and
absorb the terms used and become familiar with the class names in the sec�ons on
Physics Components
Transform Component
. You will need to know
class names to use the
Scrip�ng Reference
e�ec�vely.
Scrip�ng Reference
contains all the example code for each class. If you already know
what you're looking
for, then either do a search for the word or select it from the le� panel.
Since there are so many classes available, knowing beforehand what you need is what makes
reading the
Reference Manual
a necessity.
166 ]The following
Scenes and States
diagram shows three Scenes and nine States that we'll use
to control game �ow:
Scene0
Scene0
Scene1
Scene2
onStateScene1
onStateScene2
As you can see from this diagram, there are �ve more States and another Scene added to the
project.
We're almost star�ng fresh. Much of the code that was added in
Chapter 8
removed, and some new code has been added for this chapter.
During this ini�al tes�ng of the State Machine setup, the States will
temporarily use the Space bar and
Return
keys for switching. Also,
informa�on is displayed in the
to show the ac�ve State.
167
We're going to modify some States and create some new ones. We're also going to use
three Scenes.
In Unity
Create
three Scenes:
Build Se�ngs....
Add the three Scenes to
Temporarily add some GameObjects to
for tes�ng.
and add two
Sphere
Reload
BeginState
to edit
Edit the
constructor
method
as follows to add an
statement for
Make new C# classes for the new States. The following State Machine �les should be
coded as shown in Appendix A:
168 ]‰‰‰ ‰The StateManager file‰‰‰ ‰The IStateBase file3.   Verify that the
script is
a�ached to the
GameManager
What just happened?
You just created nine States that the game can be in. You also created three Scenes that the
game will use, determined by the State the game is in.
statement added in step 9. How did I know about
to be able to use it?
I knew I wanted the States to control the loading of the Scenes, so how is a Scene loaded
using code?
I searched the Scrip�ng Reference using terms like scene and load. It didn't actually show
exactly what I wanted, but I did see things like
That
sounded like what I wanted to do, so I clicked it. That provided all kinds of links, but to �nd
everything that's available, I needed to look at the class itself. Obviously, the class name
Reading that page showed me the variable
. This allows me to check
(level) I want is loaded. If not, then
is called
to load the
I want for that par�cular State.
The following screenshot is a side-by-side view of the Project panel and the Inspector panel,
showing
as a Component of
GameManager
169 ]With these 11 C# classes coded, the three Scenes listed in
Build Se�ngs
, the
script
a�ached to the
GameManager
GameObject, and
loaded in Unity; you should be
able to click on
Play
and see the States switch in
Console
. As shown in the previous
States
diagram, when you press the Space bar key and the
Return
key, watch the Scenes
change in the
FMlling POe ResPMrP mePOod of POe SPMPeMMnMger
This method was added to
restart the game from scratch.
method destroys the GameObject this
script is a�ached to, the
GameManager
. Why destroy it?
According to the State Machine, there are three places
is called:
At
At
At
If you have lost the game while in Scenes 1 or 2, the game needs to be restarted
from scratch.
If you have completed the game by winning in
, then you're done. Restart
the game.
When destroying the
GameManager
, there's no longer a State Machine, nor any data that was
of the State Machine. However, by calling
is loaded. Whenever
is loaded, a new
GameManager
with a�ached
is created because it's part of the
Hierarchy
Everything in a
Hierarchy
is created when a
So why wasn't a new
GameManager
created the other �mes
was loaded, such
? Actually, it was created but it was immediately
destroyed since we already had a
GameManager
method in
. This was discussed in
Chapter 8
Developing the State Machine
You may be wondering if the
GameManager
is destroyed and the State Machine with it,
then how could
be called? Needless to say, I
could have put this method before calling
, but it doesn't make any di�erence.
170 ]The GameObject isn't destroyed immediately. Look up
Destroy
Scrip�ng Reference
and you'll see this phrase:
Actual object destruc�on is always delayed un�l a�er the current Update loop, but
will always be done before rendering.
I can hear you saying that "
." Actually it is. What called
? We'll pick one of the three,
Here's the sec�on of code calling
I didn't forget
. This State will be used in
Chapter 10
Moving Around, Collisions, and Keeping Score
We need to add a GameObject named
to this game. You may use any similar shaped
GameObject of your choice that you have available, or simply use a GameObject such as a
added from the
menu. The important part is that it be named
It is going to behave like a hovercra� in the play States, so it �oats above the terrain or any
171
In the following picture, on the le� is the
Player
that was created using a �a�ened
a slightly stretched
Sphere
scale se�ngs are
Sphere
scale se�ngs are
Sphere
is renamed to
Player
Player
is required to
have it work with the code.
On the right is a simple model I'll use just because it looks a li�le bit nicer than a �oa�ng
brick. The model used isn't that important. The purpose of this model and the whole game
is to study the C# code we will be wri�ng.
Box Collider of Player
is actually moved below
Player
so the collider can detect when it
collides with the terrain. The
Is Trigger
property is checked. This makes a collider only detect
collides with another collider instead of bouncing o� it.
When it does detect colliding
with any other collider such as the terrain or any other
Player
will slowly rise up higher to get over it because ver�cal force is applied
to
Player
whenever the collider is triggered.
The collider is extended a bit to the front and rear so as it moves,
Player
can rise in advance
to go over small changes in the terrain, or other small GameObjects.
First thing to no�ce is that the
Sphere
Sphere Collider
Box Collider
instead. Since the
Player Box Collider
is being used for hovering, I used a
Box Collider
Sphere
for
Player
to actually collide with other GameObjects, and also to prevent
Player
from ever falling through the terrain.
Player
to
We also need to make changes to
GameManager
and make sure its
Transform Posi�on
Player
to
Set the
Transform Posi�on
for
Player
to
Make
Player
GameManager
by dragging
Player
onto
GameManager
. Why?
Player
needs to be able to exist in every
GameManager
is already allowed to exist in all Scenes as a result of
method called in
, any child
GameManager
will also be allowed to exist in all Scenes
I suggest adding
Direc�onal Light
to
so everything added to the Scene
Make it a child of
GameManager
as well so that all
instances will have light.
Save
Remove any GameObjects in the
Save
Remove any GameObjects in the
Finally, reload
since this is the star�ng
What just happened?
When you click on
Play
and move from one
to another, you will see the
Player
in every
Direc�onal Light
State Machine is its simplicity of control. However, a game's code
needs to access many types of data. For instance, we're going to show three splash screens.
Do we really want to �ll the State Machine itself with all kinds of variables storing image �les
and other game data? How about scoring data? Of course not, otherwise the script starts
ge�ng long and cumbersome to read.
Instead, let's create a separate Component script class whose sole purpose is to contain
game data. This way we know exactly where to look for the data when we need it, and
where to store it during the game. All we'll need to do is create a single variable in the
that points to (references) this special data script.
173
We could create a regular C# class for this, but we want to be able to assign some values in
Inspector
, so we'll
create a Unity C# Script instead. There are �mes when you will
want to use the
Inspector
g values in code is be�er.
To start, we are going to create three variables to store the images used for the three splash
screens in
By now, you should know how to create a C# Script in Unity or in
MonoDevelop. From now on, you should simply create the script
using whichever is most convenient at the �me.
folder, create a new
C# Script
, containing the
following code:
A�ach this
script to the
GameManager
to make it a Component.
All the data in all the variables will also persist through Scene changes.
What just happened?
Three variables are created to store the images for the splash screens. The variables
store values of type
174
Understanding images as textures in Unity
You have to understand that Unity
treats images as textures. Have a look at
Asset Import and Crea�on
Impor�ng Assets
. Here's a quote:
Textures
Unity supports all image formats. Even when working with layered Photoshop �les,
they are imported without disturbing the Photoshop format. This allows you to
work with a single texture �le for a very care-free and streamlined experience.
This is an example of why assigning variable values in the
Inspector
is preferred
over assigning the images using code. If you ever want to change the image, it's
Inspector
, as opposed to edi�ng code.
The �rst thing to do is
import the three images you have. If you don't have anything speci�c
already, pictures of friends or family will do nicely.
Once you have them imported, just drag them to the three variable proper�es in the
Inspector
. We have these texture images for our splash screens in the
Component, how do we get them to be displayed in the States we desire? By using Dot
Syntax, of course. We could have each State that needs to display a splash screen, call
175 ]That wouldn't be too bad with just �ve States needing splash screens. However, the
Component is for storing many types of data, not just splash screen images.
This means that
will be accessed o�en for data, and calling
State
State
176 ]Since every
State already contains a reference to
, we will have
call
An analysis of the
preceding code screenshot is given below:
object reference stores a reference to a
Component object
Therefore the type is
since other classes will be accessing this variable
177
Here's the code in
that gets the
image from
displays it on screen. It's just one line of code. I have it on three lines to �t the page:
Line 19: Code removed.
method.
method draws a
in a rectangle that is the
size of the game screen
statement is the Dot Syntax
used to retrieve the image stored in the
Component
object reference stores a reference to the
Component
variable in
stores the reference to the
Component
variable in
stores the
image
This is a direct retrieval of the image since there was no need to call
178 ]Here is the result when you click on
Play
, a fullscreen splash screen with a GUI bu�on:
For our li�le game demonstra�on, the
code is complete. There's not much
to it, a li�le State Machine code, one line of code to display the splash screen, and a line of
code to detect when to switch to

If you weren't using a State Machine, the code for controlling a
GameObject would usually be in the
method.
There will be a se�ng in the
Inspector
panel to set the rota�ng speed. Why is
Player
rota�ng
Create a
C# Script
Open it in MonoDevelop.
182 ]What just happened?
Let us analyze the code shown in the preceding screenshot:
Once again, we will add some code to
and to the
method of
The next
screenshot is of the
method of
What just happened?
Let us analyze the
code shown in the
previous two screenshots:
The variable
will store a value of type
variable is
so that it will show in the
Inspector
to modify the color
variable needs to be accessed externally by
186 ]Line 33: if(GUI.Button(new Rect(20,40,80,20), "Red"))‹‹‹ ‹The GUI.Button() method draws a bu�on on the screen with a �tle of
Red
statement detects when the bu�on is clicked
When the bu�on
is clicked,
returns a value of
Again, this is
very similar to the example in the
Scrip�ng Reference
Using Dot Syntax, the value stored in the variable
is a reference to
—the Component a�ached to
Player
method on
is called
The argument,
, is retrieving the value stored in the variable
, which is the RGBA code for the color red
This value is being passed to the
method and assigned to the
parameter variable
This is a method we create that will perform the color changing
It takes one parameter,
, that will come from calling this method in
Lines 48 and 49 are a single statement. Since it's so long, it was put on two lines.
This is just a label displayed below the spinning
Player
to let the user know to press
the Space bar to pause the spinning.
188 ]2.   As shown in the following
What just happened?
Let us analyze the code
shown in the preceding screenshots:
The variable
holds the remaining
Lives
available
This value is set using
189 ]‹‹‹ ‹The string.Format() method
is C# code that makes everything in the
parentheses a
statement is retrieving the value
stored in
before being converted to a
for display
This displays a GUI Box as a background for three bu�ons
The �tle at the top is
Player Lives
statement checks to see if a GUI Bu�on is clicked
When clicked, the value
is assigned to the variable
using Dot Syntax
These are similar to line 36 except for the value assigned to
With all this coding complete,
you should have
looking like this when in
If you are using
instead, perhaps you have something like this:
Player
speed is what I happen to like. Change it to your liking in the
Inspector
and then modify the variable in code so this spin speed will always be the default se�ng.
Remember, changing the se�ng in the
Inspector
does not change any code �les.
v1. For wri�ng scripts, what are the two primary Unity documents you should use?
v2. What normally happens to exis�ng GameObjects when a new
Q3. The States require access to data stored on
. Why do the States use
to access this data instead of directly accessing
Player
is added to the
Hierarchy
, why is it made a child GameObject
GameManager
191 ]Summary
We looked into using Unity's
Reference Manual
and the
Scrip�ng Reference
. As a
beginner, probably the most �me consuming part of wri�ng code will be searching Unity's
documenta�on for the informa�on you need. We expanded the State Machine and added a
Player
GameObject. Planning ahead before wri�ng code is always a good idea. A State Machine
is a good op�on for organizing your project's code. Nine State classes were created for the
State machine. We then displayed a splash screen and a bu�on in
. For the
As we enter the PlayStates, the Player needs to be able to move around in the
Scene. A common way to move the Player is by using the Transform Component
methods. However, we really want to use Rigidbody physics instead.
With all this moving around, it would be nice if we could always see what the
Player is doing. We'll see a couple of ways the camera can keep an eye on the
Player's movements.
To demonstrate game code, we'll have some good and bad GameObjects that
the Player can interact with. The good objects will increase the score, and the
bad objects will decrease the life of the Player.
In this chapter, we shall study:
Star�ng in Scene1
Camera views
Moving Player using Rigidbody physics
Keeping score
Shoo�ng projec�les
Let's see how all of these �e together...
194 ]VisuMlizing POe complePed gMmeAs simplis�c as this
game is for learning C#, it's s�ll nice to have some sort of picture of a
game when complete. The primary goal is learning how separate pieces of code can come
together to form a whole game.
The following screenshot was taken while in
Player
several energy pulses. Of course, your assets will probably look di�erent, but this chapter
completes all the coding necessary to have a simple func�oning game.
This chapter is going to be structured slightly di�erently than the previous
chapters. Instead of going through step-by-step instruc�ons to add code to our
classes and scripts, all the complete �les of code can be found in
I will simply reference the relevant code when doing a code �ow analysis.
Chapter 9
Start Building a Game and Get the Basic Structure Running
An analysis of the code shown in the preceding screenshot is as follows:
Player
near the center of the Terrain
Player
will use physics to hover and move. Here is the relevant code in
An analysis of the code shown in the preceding screenshot is as follows:
We were in
, so this condi�on is
is not loaded, therefore:
variable
will store a
which we'll �nd in line 18
method is used to �nd the
Player
Hierarchy
A reference to the
Player
GameObject is assigned to the variable
Player
isn't found,
will be storing
which will create an error in line 19
With a reference to
Player
, we can access its
Component stored in the
variable
The variable
is assigned the value
Player
GameObject is now a�ected by physics in
has two
possible States the game can be in:
State
State
Each State will demonstrate using a di�erent camera and a di�erent way to keep focused on
Player
as it moves around.
Camera 1 will be posi�oned above and at the center of the
Terrain
. Camera 2 moves to
follow
Player
around the
We'll have three cameras, but only one will be ac�ve at a �me. Their names are:
Main Camera
LookAt Camera
Following Camera
Do the following steps with
loaded to add two cameras:
Camera
Set its
Transform Posi�on
to
Ac�ve
checkbox.
197 ]4.   Add a Camera
Ac�ve
checkbox.
Drag both of these cameras onto
GameManager
to make them children.
Scrip�ng Reference
for
GameObject.SetAc�ve
. It's a method to set whether a
GameObject is ac�ve or not. However, Unity can't �nd an inac�ve GameObject using the
method. So we'll store a reference to each camera in a List.
Line 10 in the following screenshot of the
script creates the List to store the
three cameras:
Now we'll add
all the cameras in
to the List:
GameManager
Hierarchy
Inspector.
Game Data
(Script).
Set the
Size
Cameras List
to
Now drag the three cameras from
Hierarchy
to
Cameras Elements:
It doesn't ma�er which camera is stored in any of the Elements.
Now that we have references to all cameras, whether they are ac�ve or not, we have the
ability to make a camera ac�ve in code.
in MonoDevelop.
Add code lines 21 through 27 as shown in the following screenshot:
What just happened?
Let us analyze the
code that we just saw:
loop retrieves each camera in the List named
As each camera is retrieved, it's assigned to the variable
loop iterates through the List, if the camera retrieved is not named
LookAt Camera
, then line 24 is executed
LookAt Camera
, then line 26 is executed
Switching to
makes the
Following Camera
ac�ve:
iterates though the List,
LookAt Camera
will be set as inac�ve, and
Following Camera
will be set to ac�ve.
LookAt Camera
Following Camera
each have a script a�ached.
This simple script makes the
camera look at
Player
The camera does not move. It simply
rotates so it's always looking at
Player
no ma�er how close or far away it is.
A�ach this script to
LookAt Camera
Hierarchy
What just happened?
Let us analyze the
code that we just saw:
variable
will store the
informa�on of
Player
that every frame, the
x, y, z posi�on of
Player
is updated
and stored in the variable
In order to store the
Player
, the script �rst needs a reference
Player
GameObject by using
Player
is retrieved and stored in the variable
Lookup
LateUpdate
Scrip�ng Reference
, here's a quote:
...a follow camera should always be implemented in LateUpdate because it tracks
objects that might have moved inside Update.
method
is available in the
This is the method that makes the camera's
rota�on change so it's
always looking at the target, which is the
posi�on of
Player
This camera script has
three added lines of
code to make the camera move as
Player
moves.
A�ach this script to
Following Camera
Hierarchy
201 ]What just happened?
An analysis of the
code shown in
the preceding screenshot is as follows:
The variable
stores the distance the camera will be above
Player
The variable
stores the distance the camera will be away from
Player
on the x and z axes
The variable
stores the
data of
Player
, but all we
want to know is the
data from all that
data
Therefore,
stores the constantly changing x, y, z
Player
The height and distance data stored in
can
be added to the data of
Player
to specify where the camera should be located
The variables are
plugged into the
tor3 x, y, z posi�ons and added to the
Player
We want to add a
Component to
Player
, and use gravity.
Moving
accomplished by applying a force to
Player
physics, Unity tells us to use the
method, not the
method.
Crea�ng GamePlay
Physics
. Here's a quote:
If you move the Transform of a non-Kinema�c Rigidbody directly it may not collide
correctly with other objects. Instead you should move a Rigidbody by applying
forces and torque to it.
Also, look in
Scrip�ng Reference
MonoBehaviour.FixedUpdate
FixedUpdate should be used instead of Update when dealing with Rigidbody. For
example when adding a force to a rigidbody, you have to apply the force every
�xed frame inside FixedUpdate instead of every frame inside Update.
We're going to add a
Component to apply physics to
Player
. To stop
Player
from
dropping like a rock, out of view of the camera, we'll check
Is Kinema�c
proper�es to turn o� the e�ect of physics. When any of the play States are ac�ve, we'll
Is Kinema�c
in code to allow physics to a�ect
Player
Player
Hierarchy
At the bo�om of the
Inspector
panel,navigate to
Add Component
Physics
Component, check
Is Kinema�c
The following screenshot shows the code for moving
Player
using physics forces:
What just happened?
Inspector
values stored in the
variables under
proper�es a�ect the move ability of
Player
just like in real life.
203 ]In any play State,
Is Kinema�c
is unchecked allowing physics to work.
An analysis of the code we saw in the preceding code screenshot is as follows:
Note that
is being used directly in
instead of being
controlled by the State Machine:
The State
Machine is controlling the
se�ng
is checked, physics code does not work to move
Player
there's no need to have the State Machine controlling
This variable will be used as a mul�plier to make the forward and backward speed of
Player
faster
This variable will be used as a mul�plier to make
Player
rotate faster
205 ]When we lose, we have the op�on to retry the
. To do this, the system needs to
remember what the
Score
Player Lives
were when �rst entering the
so they can
be reset back to these values.
The following two
screenshots show the code for ini�alizing the score:
The following steps
occur while the game is in the setup State of the game.
An analysis of the code shown in the preceding two screenshots is as follows:
206 ]Step 1:
From
Chapter 9
Start Building a Game and Get the Basic Structure Running
, we already have
the variables for keeping track of the
Score
Player Lives
during gameplay:
variable on line 16
variable on line 18
We need two more variables to remember the values stored in
The
variable stores the
Player Lives
selected in
207 ]Line 33: playerLivesSelected = livesSelected;‹‹‹ ‹The value is assigned to
The value now in
is remembered for the whole game
variable
is also assigned to
to be displayed
on screen
The user has now switched from the setup State to playing the game in
There are two possible play
States in
. For the scoring
system, they both have the
exact same code in their
methods, so I will only explain the code in
The following screenshot shows the code for checking the
Score
to see if we win, and
Player Lives
to see if we lose:
An analysis of the code shown in the preceding screenshot is given in the
following subsec�ons:
Step 5:
This step is
executed if we lost in
208 ]Line 32: if(manager.gameDataRef.playerLives = 0)‹‹‹ ‹This if statement
checks to see if
has decreased to zero
Since we lost, the State Machine switches to
Is Kinema�c
op�on is checked to stop
Player
from being a�ected by physics
Player
GameObject is reposi�oned back to the beginning posi�on for
to
be replayed
209 ]Line 40: Line 40: if(manager.gameDataRef.score = 2)‹‹‹ ‹This if statement
checks to see if
has increased to 2
Is Kinema�c
op�on is checked to stop
Player
from being a�ected by physics
Player
GameObject is posi�oned for
Since we
won, the State Machine switches to
Step 8:
211 ]An analysis of the
code we saw in the preceding code screenshot is as follows:
This is a copy and paste from the example code in the
Scrip�ng Reference
Player Box Collider
Is Trigger
Player Box Collider
runs into the another GameObject with a
Unity calls the
method
The variable
now stores a reference to the
that
Player
ran into
We are checking to see if the GameObject that the
is a�ached to has
tag
is increased by 1
method is removing
from the
All it takes to lose is for
the value in the variable
to be 0.
To decrease
Player
will collide with a
variable
will decrease by 1, and the
will disappear from the
An analysis of the code
we saw in the preceding code screenshot is as follows:
This code is similar to
. However, since we are using
, we have to use a
that does not have
Is Trigger
checked.
Player
Sphere
Box Collider
crashes
into a
Player
will lose a life.
Player
runs into another GameObject with a
that is not a trigger,
Unity automa�cally calls
variable now stores a reference to the
that
Player
ran into
No�ce that
Collider
, as opposed to triggers, require using the
This checks if the GameObject
Player
collided with has a tag named
is decreased by 1
method removes
from the
There is a way to increase
Player Lives
. By shoo�ng a
, the variable
will be increased by 1. It also turns a
into a
has no code for shoo�ng.
has code to
EnergyPulse
at a �me. In
has con�nuous rapid
�re shoo�ng.
To get the appearance of an
EnergyPulse
, we will actually shoot a
Sphere
. We won't see the
Sphere
because its rendering will be unchecked. The
EnergyPulse
e�ect is created by using a
Trail Renderer
e�ect on the
Sphere
We need to create a prefab
EnergyPulse
projec�le. Use the following screenshot of
Inspector
as a guide for these steps.
Create a new prefab by naviga�ng to
Assets
Create
Prefab
Sphere
to the
Posi�on its
Transform
to
213 ]4.   Scale its
Transform
to
Sphere Collider
Is Trigger
Mesh Renderer
Component.
Turn o�
Gravity
Add the script
Trail Renderer
Component by naviga�ng to
Component
E�ects
Trail Renderer
Drag a
prefab to the
property on the
Energy Pulse Power (Script)
Set the
Trail Renderer
proper�es as shown in the following screenshot.
Drag
Sphere
onto the newly created, empty
EnergyPulse
prefab.
Now delete
Sphere
from
214 ]What just happened?
Now that we have
EnergyPulse
to shoot, we can shoot them in two States:
only allows a
single shot to be �red for each press of the key.
An analysis of the code we saw in the preceding code screenshot is as follows:
An analysis of the code we saw in the preceding code screenshot is as follows:
215 ]TOe EnergyPulse is �redIn PlayerControl, the EnergyPulse
is instan�ated in front of
Player
, and force is used
to propel it forward. The
EnergyPulse
has to be instan�ated in front of
Player
so that the
EnergyPulse Collider
doesn't detect
Player Collider
immediately a�er being instan�ated.
If it does detect it, the
EnergyPulse
will be destroyed immediately.
script needs to know about the
EnergyPulse
prefab so that it can
be created in code. Drag the
EnergyPulse
prefab to the
Projec�le
variable property in
Inspector
An analysis of the code
we saw in the preceding code screenshot is as follows:
stores the
EnergyPulse
prefab so it can be instan�ated
216 ]Line 56: public void FireEnergyPulse()‹‹‹ ‹This is called by
stores a reference to the new
object about to be created
Since we will be using physics force to propel the
EnergyPulse
forward, the variable
method
takes the
Prefab
stored in the variable
and creates an
EnergyPulse
The method also places in it at the same posi�on as
Player
but we'll �x this
Since the variable
stores a
EnergyPulse
EnergyPulse
has to be converted to a
operator will cast (convert) the GameObject to a Rigidbody
Since we can't have the
EnergyPulse
object at the same posi�on as
Player
moves it in front of
Player
before the frame is ready to display
This sets the
being applied to move
EnergyPulse
forward
We now have our
EnergyPulse
being �red. Now we need to make things happen when it hits
something.
Player
EnergyPulse
, what happens next? Does it just go on forever? What
something?
We certainly don't want these instan�ated
EnergyPulse
Gameobjects hanging around
forever. Once they've served their purpose, they should be destroyed. That's exactly what we
do. A�er a set �me, they simply disappear.
EnergyPulse
is meant to do two things:
Increase
Player Lives
Convert a
into a
217 ]Anything else they hit is immune to the e�ects of the
EnergyPulse
. The following screenshot
shows how this is done:
An analysis of the
code we saw in the preceding code screenshot is as follows:
script is a�ached to the
EnergyPulse
This sets how long an
EnergyPulse
will exist
This �me is adjustable in the
Inspector
This is a countdown �mer that operates at the rate of
per second
When the value in
reaches
, line 15 is executed
Since this script is a�ached to the
EnergyPulse
EnergyPulse
destroyed when the �mer reaches 0
That makes sure an
EnergyPulse
does not last forever.
218 ]Now we look into increasing
Player Lives
and conver�ng
BadOrbs
into
GoodOrbs
. What
happens is that a
collides with an
EnergyPulse
is destroyed and
disappears.
A new
is instan�ated and placed exactly where the
to be, giving the appearance that it was converted.
variable stores the
prefab so it can be instan�ated
This method is called by Unity when the
Sphere Collider
EnergyPulse
hits any
variable now stores a reference to the
of the GameObject that
was hit
If the hit GameObject's tag is
, then the code block is executed
If it does not have a tag of
, then line 28 is executed
is instan�ated and placed right where
is located
This destroys the
gameObject
EnergyPulse
hit something, so it is destroyed and disappears
EnergyPulse
hits something it is destroyed and disappears
This is executed when
EnergyPulse
hits anything other than a
HMve M go Oero – MnMlyzing POe code for POe second level of plMy
is very similar to
. It's included to show the ability to have a game with more
than one level of play. Switching to the
State is just as easy as switching to
any other State. I did not explain the code for
because it would be redundant analysis.
You already know all the fundamentals and concepts to be able to look at the code and know
how it works. The challenge for you is to analyze the classes and code for
, and in the
process realize that you now have the ability to do just that, read and understand code.
Pop quiz – knoRing ROicO UniPy mePOods Po cMll
v1. Using code, what are the two ways to move a GameObject in a game?
v2. When applying a force to a GameObject to move it, what method should be used? (Hint:
v3. When wan�ng to �re a projec�le that doesn't even exist in the scene, how do you get
one to appear in the game?
v4. To display bu�ons and text on the game screen, what Unity method is used?
Summary
Even though this simple game wasn't much to look at, its sole purpose was to show you how
small sec�ons of code are brought together to form a game. We used C# to turn Rigidbody
physics on and o� for
Player
, and moved the Player using physics forces. A couple of extra
cameras were added to provide two ways to follow the Player. We created a scoring system
that's displayed on screen during the game. Finally, we covered detec�ng and using collision
and trigger events.
In the �nal chapter, we'll review your new C# skills and where to go from here to con�nue
your educa�on.
Summarizing Your New Coding Skills
When you initially started with this book, all the little details about programming
looked like a treacherous mountain to climb. Every step up the mountain was
perceived as the one that would just be too difficult to take. Learning to write
C# code looked nearly impossible to learn. Not because each step is difficult, but
because it looked like a mountain of information to overcome. Then the journey
began and a funny thing happened along the way. Each step became just another
step. Before long, the top was reached and the goal was accomplished. All that
initial fear and worry was nothing more than overzealous imagination.
Now that the top is reached, we'll turn around and look at the new skills you
just learned, and mention some things that weren't learned during your hike up
this mountain.
In this chapter we will cover the following topics:
Review the goal of this book
Look at the C# you learned, and didn't learn
Look at the State Machine as a design choice
Talk about furthering your educa�on
Let's see where to go from here.
222 ]Coding a Unity Project
Unity projects
are usually about the game being created, and not the code used to control the
game. The State Machine was the project for this book; not the actual game. The simple game
was just a collec�on of examples to demonstrate coding to access some of Unity's features.
The point of this book is to teach the basics of programming using C#. The State Machine
allowed me to teach you about C# classes that were not Unity scripts. As you learned,
not all classes have to be a script a�ached to a GameObject. If a class doesn't use any of
Unity's magic methods, such as
, and none of the variables need
to appear in the
Inspector
panel, then you could just create a regular C# class instead of a
Component script.
None of the State classes are Components so they don't have to inherit from
, yet they allow �ne control of the game while organizing the code. Instead
of having many large scripts with many
statements to determine game �ow, a few
compact States were used when needed.
We saw that in Unity, everything is an object that contains data in variables, and methods to
work with the data. For instance, the
object knew its color, how fast it could move,
and that it could
shoot projec�les. The projec�le object knew how long it would exist, how
fast it travelled, and what to do when it encountered another object. The objects know what
to do because their behaviors were de�ned in a class �le.
This interac�on between objects is possible because they could talk to each other by using
dot syntax communica�on. The class de�nes what an object should or shouldn't do when
encountering with another object. The
object knew it should try to hover over other
GameObjects. However, if it instead collided with certain GameObjects,
other GameObjects communicated with each other to cause speci�c ac�ons to take place,
such as changing the score.
Even though classes are nice from a coding point of view, the basic thing to understand
is that a class simply consists of the two main building blocks of programming, variables
and methods.
No ma�er what feature C# may have that makes wri�ng code easier, everything revolves
around variables to store data, and methods to act on the data. That's why the �rst goal
of this book was to help you understand these building blocks.
223 ]ScrMPcOing POe surfMce of F# progrMmming
We learned many ways
to work with data. The code inside a method is where all the
work is performed on the data, such as using the data to make decisions or modifying the
data value. Even when Dot Syntax extracted data from another objects, all the work was
performed in a method.
The C# code we used was rather basic, but we accomplished everything needed to create
our game. Once again, that was the purpose of this book, to teach you the fundamental
concepts of programming and use basic C# coding techniques to get the job done.
There are more C# techniques we could have used to make our code more e�cient, and you
may want
to learn more about C#. But if you just want to understand enough C# to get some
scripts wri�en that are basic and easy to understand, then that's �ne.
Understanding concepts can take a while to sink in before the lights turn on. So keeping
the learning list short is important for a beginning programmer. This allows the basic
concepts to be well-established before trying to learn some of the more advanced features
of C# programming.
Some of the C# areas we didn't cover that you may want to look into are enumera�ons and
switch statements.
This could be useful to use to replace a lot of
statements when
C# proper�es are slightly more advanced version of using variables. They allow more control
over accessing or se�ng the data the variable will store.
Then there's even more advanced features such as the use of delegates or re�ec�on
features, which are de�nitely not appropriate for a beginner's book.
It all depends on what your goal happens to be, to get some simple scripts wri�en or to
make your code as e�cient as possible with as few lines of code possible.
Just keep this simple rule in mind,
write your code simple enough so another programmer
can easily understand what it does, because in six months, you'll be that other programmer
As you write your scripts, you know how it works and what it's supposed to do because
you're wri�ng it right now. In six months, all you will have is a vague memory of the code you
write today, if you're lucky. I will bet that if your code isn't easily understandable, then in six
month or more when you need to make a change, you'll come back and look at your code
and say "What the heck is this trying to do? Who wrote this mess?"
224
Iooking MP even more UniPy feMPures
There are many Unity
speci�c items not covered in this C# book. For example, we didn't
speci�cally cover saving any data to disk, nor did we look at how to use corou�nes.
This book would have been extremely long if everything about scrip�ng was covered. It
would have been much larger than the
Scrip�ng Reference
. It also would have made you
think you needed to learn everything before diving in and trying to write a code.
Remember that the Unity documenta�on is there so you don't have to know everything.
With the basics of wri�ng code under your belt, you can look into the
Reference Manual
Scrip�ng Reference
to get and understand the code you want when it's needed.
Scrip�ng Reference
documents all the behaviors you can apply to a GameObject. When
you look in the
Scrip�ng Reference
for a speci�c behavior, you are given the methods and
variables needed, and some code to show you how to use them. Some�mes you may be able
to use the example code as it is; but some�mes you'll need to modify the example code to �t
your needs.
The point is, you know the fundamentals of variables, methods, and Dot Syntax. It will now
be a lot easier to look at code examples in the
Scrip�ng Reference
and �gure out the details
of its opera�on, and then apply it according to your needs.
Just like your daily rou�nes, you follow certain pa�erns that are comfortable to you. Why is
that? Probably because it's easy for you and they're etched in your brain; they're habits.
Whatever it is you do;
sort your laundry, build a sandwich, wash the dishes, work with
Unity, you will eventually develop a rou�ne pa�ern that you'll follow and like. You can
equally believe that you will establish a pa�ern for wri�ng scripts, too. Right now, a�er
reading this book, you may already have some idea of how you will write and add scripts
to GameObjects. Maybe you're already quite pro�cient at everything in Unity except
for the scrip�ng part. All you may want is to write some scripts and a�ach them to your
GameObjects, then get back to doing the fun stu�.
How you design your scripts to control your game can be simple and neat, or if you're not
careful, it could turn into a spaghe� nightmare that will make you pull out your hair. Just
haphazardly wri�ng scripts will not make you happy, especially if you need to make changes
in your game �ow at a later �me.
225 ]Using a State Machine is a design pattern choiceAs you discovered, each ac�ve State allows you to control what Unity does and what it displays.
It organized our code
making it simple, neat, and easy to follow. I happen to like it. You may
have decided that you don't like the idea of a State Machine a�er seeing the version in this
book. Every programmer develops their own rou�ne for coding. The point is, you will decide
what's easiest for you and establish a pa�ern that's comfortable.
Besides showing you why I like State Machines, I also exposed you to wri�ng regular C#
classes. I also expanded a li�le into using a C# interface as well. A C# interface could be used
easily with Unity Component classes as well. I just happened to need this C# feature for the
State Machine classes.
Our State Machine
was used to control the whole game. You could just as easily use this
State Machine design pa�ern at the GameObject level as well.
Our game State Machine used the
object. This was a Component a�ached
to the empty
GameManager
panel. Its primary job was to know which State
was ac�ve during the game.
For a visible GameObject such as an enemy, you could control its allowed ac�ons for various
condi�ons. You would basically name the a�ached Component script something like
. The following graphic shows a possible enemy State Machine:
A
ttackPlayerState
F
ollowPlayerState
An alternate to using this type of State Machine is that you could code a GameObject State
Machine using a combina�on of a C# enumera�on and a switch statement.
226 ]That's the neat
thing about programming. There are countless way to write code to get the
desired result and behavior.
I personally prefer to have many very small class �les that do one task rather than having one
huge class �le that does many things by using endless lines of
statements or long
switch statements. You will eventually determine your preferred way of doing things.
227 ]VisiP my fMvoriPe ReNsiPe for F#I actually only have one website that I really like for learning C# speci�c code:
C# Tutorial: Dot Net Perls: You can
nd this at
These are the State Machine �les men�oned at the beginning of
Chapter 9
Start Building a
Game and Get the Basic Structure Running
, necessary for our Unity project.
BeginState
SetupState
PlayStateScene1_1: (1 of 2 available States in Scene1)
PlayStateScene1_2: (2 of 2 available States in Scene1)
WonStateScene1
LostStateScene1
PlayStateScene2
WonStateScene2
LostStateScene2
StateManager
IStateBase
This is how the �les should be coded to begin
Chapter 9
Start Building a Game and Get
These make the State Machine func�onal for switching States
Each one will be modi�ed as we progress through
Chapters 9
Start Building a Game and Get
Chapter 10
Moving Around, Collisions, and Keeping Score
private StateManager manager;

public void StateUpdate()
{
{
manager.SwitchState (new
}
}
}
public void ShowIt()
{
Debug.Log("In WonStateScene1");
}
{
Debug.Log("In LostStateScene1");
}
}
237
{
instanceRef = this;
}
else
{
DestroyImmediate(gameObject);
void Start ()
{
activeState = new BeginState(this);
}
void Update()
{
if (activeState != null)
activeState.StateUpdate();
void OnGUI()
{
public void SwitchState(IStateBase newState)
{
activeState = newState;
}
public void Restart()
{
Destroy(gameObject);
Application.LoadLevel("Scene0");
}
}

242
243
244
245
246
247
248
249
{
public class PlayStateScene2 : IStateBase
private StateManager manager;
private GameObject player;
private PlayerControl controller;
public PlayStateScene2 (StateManager managerRef)
{

player = GameObject.Find("Player");
251
252
if (GUI.Button(new Rect(10, 10, 270, 30),
"Click Here or Space key to repeat Level") ||
}
}
void Start ()
{
activeState = new BeginState(this);
public float hoverPower = 3.5f;
public Rigidbody projectile;
public Color red = Color.red;
public Color blue = Color.blue;
public Color green = Color.green;
public Color yellow = Color.yellow;
private GameData gameDataRef;
void Start ()
{
gameDataRef = GameObject.Find("GameManager").
gameDataRef.playerLives -= 1;
Destroy(collidedWith.gameObject);
}

public void FireEnergyPulse()
{
transform.rotation) as Rigidbody;
clone.transform.Translate(0, .5f, 2.1f);
clone.velocity = transform.
TransformDirection(Vector3.forward * 50);
}
public void PickedColor (Color playerColor)
{
renderer.material.color = playerColor;
public class GameData : MonoBehaviour
{
257
using System.Collections;
public class FollowingPlayer : MonoBehaviour
{
-cameraDistance);
transform.LookAt(playerPosition);
public class EnergyPulsePower : MonoBehaviour
{
Destroy(gameObject);
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "BadOrb")
{
transform.rotation);
GameObject.Find("GameManager).
FOMpPer 1, Giscovering Kour Hidden ScripPing Skills
The false perception that writing code is too difficult.
Unity's Reference Manual.
None. It's a reference document, which means you look things up as you need them.
When the new file appears in Unity's Project tab, it appears with the filename in
edit mode. Renaming the file immediately will make the class name the same as the
FOMpPer 2, HnProducing POe Building Blocks for UniPy
To store some data that will be substituted into a script somewhere.
To execute some code that will be needed several times.
By attaching the script file to a GameObject.
To have access to variables and methods on other Components.
262
Begin the name with a lowercase letter. For multiword names, a variable can
only be one actual word, so spaces are removed between the words, and then
capitalize the first letter of each word.
Declare the variable as public.
No, only member variables can be public.
A variable can only store one type of data, which has to be specified when it's
declared.
Specifying the type of data returned from the method, the name of the method
with parenthesis, and a pair of curly braces for the code block.
To allow data to be passed into the code block.
It means the method is not returning any data to the code that called the
method.
method is called automatically by Unity if the script inherits
from
True or false.
The NOT operator, which is the exclamation mark (
The AND operator, which is two ampersand signs (
The OR operator, which is a double-bat (
The location in an array, or a List, where data is stored.
The first element in an array, or a List, has an index number of zero. This is called
zero indexed.
No. When an array or a List is declared, the type of data it can store is specified,
and only that type can be stored in its elements.
An array cannot be dynamically expanded. Once an array is initialized, it can't
change its size. This is why a List is more flexible. A List can change dynamically.
It's an address for locating public variables and methods.
A reference to the object. The object itself is not stored in the variable. A reference
points to the actual object so that the variables and methods of the object can be
Dot Syntax allows access to any GameObject or any of its Components, however,
the variables and methods on other Components must be public.
A member variable of a Component can appear in the Inspector by making the
variable public, and then a GameObject can be dragged-and-dropped into the
Property (variable)
Inspector
FOMpPer 7, FreMPing POe GMmeplMy is JusP M PMrP of
Helps keep code very organized.
A State Machine has a controller that is a Unity script, which is attached
to a GameObject. The State Machine controller in this book is named
, which calls the methods on a particular State.
There is no limit. Use as many as needed for controlling gameflow.
A C# interface specifies the methods each State has to implement.
The State classes also inherit the
interface. This means every State
object, allowing the
variable to store
any of the State objects.
script has the
method and the
method.
method calls
calls
All GameObjects in the current Scene are destroyed.
Absolutely false. Adding States, removing States, and changing the order that the
States can switch are a few of the greatest benefits of a State Machine.
FOMpPer E, SPMrP Building M GMme Mnd GeP POe BMsic
The Reference Manual and the Scripting Reference.
They are destroyed.
Each State would need to call the
FOMpPer 10, Moving Around, Follisions, Mnd Keeping Score
Pop quiz – knoRing ROicO UniPy mePOods Po cMll
By changing the transform coordinates of the GameObject, or by adding Rigidbody to
the GameObject and applying a force.
Unity highly recommends using the
method.
First, in the
Projectile
GameObject is created to be made into a
Prefab. To get one into the running game, you have to instantiate the Prefab using the
method.
method.
Index
access modi�ers
using, for methods 91
using, for variables 91
ac�ve State
game Scene, pausing 145
ac�veState variable 133
AddTwoNumbers(), using 51-54
AddTwoNumbers() method 26, 27, 51
Applica�on Programming Interface (API) 123
Awake() method
adding, to StateManager 154, 155
BeginState
�mer, crea�ng 147-151
BeginState class
instan�a�ng 121, 122
BeginState() method 121
bene�ts, State Machine 113
built-in variable types
values, assigning 38, 39
choosing, reasons 10, 11
website 227
cameras
adding, for di�erent viewing op�ons 196-199
scripts, a�aching to 199
C# interface 123
crea�ng 118-120
instan�a�ng 118
class, instan�a�ng
class, crea�ng 118-120
code �les, loca�ng with using statement 123
�le loca�on, specifying with namespace
declara�on 122
script, crea�ng 118-120
crea�ng 117, 118
code block 40
code �les
loca�ng, with using statement 123
coding skills
applying, to State Machine 112
Collec�on Ini�alizer
used, for items adding to List 75, 76
completed game
component objects
crea�ng 117
component proper�es, Unity Inspector
property value, changing 33
script name, changing 33
variables, conver�ng to 33
components 9
C# programming surface
C# features 223
scratching 223
Unity features 224
C# script �les
crea�ng 14
LearningScript in MonoDevelop, opening 15
MonoDevelop code editor 15
sync, �xing 16
syncing, between MonoDevelop and Unity 15
C# statements
curly braces
used, for method de�ni�on ending 44
simplifying, in Dot Syntax 90
Dot Syntax
components, communica�ng 29
dots, simplifying 90
using, in script 93
Dot Syntax, in script
code analysis 99-107
component, accessing on current GameObject
methods, accessing of components 93
variables, accessing of components 93-96
drag-and-drop
used, for assigning GameObjects 108, 109
EnergyPulse Prefab
crea�ng 212-214
EnergyPulses
objects, controlling 216-219
�le loca�on
specifying, with namespace declara�on 122
FireEnergyPulse() method 214
FollowingPlayer camera script
a�aching 199-201
foreach loop
used, for data retrieving 77-80
for loop
used, for pony selec�on 81-83
Frames per Second.
methods
game
losing score 211
winning score 210, 211
game controlling
delega�ng, to state 114
State Machine, using 225
GameData script
images as textures 174
splash screens, displaying 174-179
splash screens, using between game levels 174
GameObject.Find() method 197
assigning, drag-and-drop used 108, 109
crea�ng 102-104
Gameplay 111
game scene
changing, �mer used 147
game score
ini�alizing, code 205
in Scene1 play State 207
scoring system, ini�alizing 205-207
if-else statement
else, adding to 63, 64
using, for alternate code execu�on 63
if statement
crea�ng 58, 59
crea�ng, with mul�ple condi�on check 60, 61
tes�ng condi�ons 58
Inspector pane 28
Inspector panel
public variables, displaying 34, 35
instan�ate keyword 117
Instan�ate() method 216
interface guarantee, State Machine 124
IStateBase interface
code �ow 138-141
code �ow, summarizing 141
entering 136
features 137
StateManager, modifying 137, 138
items
accessing, in list 66
adding, Collec�on Ini�alizer used 75
storing, in array 66, 67
storing, in dic�onary 73
storing, in List 68
items, storing in dic�onary
pony name dic�onary, crea�ng 73, 74
items, storing in List
pony name list, crea�ng 68-72
Key 73
LearningScript variables 37
List
looping through 77
Lives op�on
se�ng, for Player GameObject 187-190
LookAT() method 200
LostStates class 161, 165
method de�ni�on
parameters, coun�ng 49
parameters, specifying 48, 49
method names 45
methods
arguments, using in parenthesis 49, 50
begin method names 45
calling 49
de�ning 45
de�ning, minimum requirements 46-48
in script �le 25
mul�-word names, using 45
parenthesis, using 45
subs�tute 25, 26
using, in script 24
value, returning 50, 51
working 24
MonoBehaviour class 114
MonoBehaviour method 54
MonoDevelop code editor 15
namespace declara�on
�le loca�on, specifying with 122
Object Oriented Programming (OOP) 20, 129
working with 91-93
OnGUI() method
adding, to StateManager 143
adding, to StateManager controller 143
PickedColor() method 186
playable scene
switching to 194
Play bu�on 28
Player
moving, Rigidbody physics used 201-204
Player Collider
Player Color op�on
color modi�ca�on, GUI bu�ons used 184-187
Player GameObject
controlling 179
Lives op�on, adding 187
Player Color op�on, adding 183-187
rota�ng, in SetupState 180-182
play State
switching to 194
PlayStates class 165
PlayState to add another State
modifying 142
prefab 210
rapid-�re EnergyPulses
reference manual documenta�on, transform
component
ResetPlayer() method 208
Return/Enter key 27, 142
Rigidbody physics
used, for Player moving 201-204
Rotate() method 183
Scene1, Player
Scene1 play State
game level, winning 208, 209
game, losing 207, 208
level, winning 209
losing strategy 208
prefabs, crea�ng 210
score, keeping 207
winning strategy 208, 210
another Scene, se�ng up 152, 153
Awake() method, adding to StateManager 154
bu�on, adding 144, 145
controlling 144
changing, by code addi�ons 157
changing, side e�ect 153
class code, verifying 157-161
GameManager, inser�ng between 153
Scenes and States diagram 166
screenDura�on variable 148
script
crea�ng 118-120
crea�ng variable, working 22, 23
Dot Syntax, using in 93
methods, using 44
number, modifying to di�erent number 23, 24
variable, ac�ons 20, 21
variable name, as value subs�tute 21
variable, naming 21
scrip�ng documenta�on, Unity
Unity Reference Manual, code examples 165
Unity Reference Manual, reading 165
Scrip�ng Reference 11, 123
scrip�ng reference documenta�on, transform
component
scriptphobia
GameObjects, behaviors 9
scripts, a�aching to cameras
FollowingPlayer camera script 200, 201
LookAtPlayer camera script 199
SetPlayer() method 206
SetupState class 165
ShowIt() method 143
single-shoot EnergyPulse
Start() method 55
state
game control, delega�ng to 114
State classes
BeginState, modifying 130-132
StateFixedUpdate() method 127
State Machine
bene�ts 113
coding skills, applying to 112
GameData script, crea�ng 173
game data, storing 172
interface guarantee 124
interface, implemen�ng 124-127
se�ng up 165, 166
se�ng up, in MonoDevelop 167-169
se�ng up, in Unity 167
Unity project, controlling 113
used, for game controlling 224
using, at GameObject level 225, 226
State Machine logic �ow
ac�ve state, tracking 116
game control, delega�ng to state 114
state, switching 115
StateManager
Restart() method 169, 170
StateManager class 158
StateManager controller
another State, adding 142
inheritance example 134, 135
IStateBase interface, entering 136, 137
se�ng up 132
StateManager script
features 114
States and Scenes diagram 169
StateUpdate() method 115, 132
string.Format() method 189
Switch() method 150
SwitchState() method 140
tes�ng condi�ons, if statement
changing, NOT operator used 60
false 58
heBearMadeBigPo�yInTheWoods, changing 63
mul�ple condi�ons, checking 60-62
MonoDevelop, se�ng up 167-169
scrip�ng documenta�on 164
State Machine, se�ng up 167
working in, Game-Creator hat used 28
Unity coding
website 227
Unity Inspector
component proper�es 32
Unity Project
coding 222
Update() method 55, 56, 170
using statement
code �les, loca�ng with 123
value, returning from methods
AddTwoNumbers(), using 51-54
variables
built-in variable types 38
declaring, loca�on 39
mul�-word variable names, using 36
naming, conven�ons 36
scope 40, 41
breakout, �nding 84-87
data, �nding 84-86
WonState class 151, 160, 165
Thank you for buying
Learning C# by Developing Games with
About Packt Publishing
Packt, pronounced 'packed', published its �rst book "Mastering phpMyAdmin for E�ec�ve MySvL
Management" in April 2004 and subsequently con�nued to specialize in publishing highly focused
books on speci�c technologies and solu�ons.
Our books and publica�ons share the experiences of your fellow IT professionals in adap�ng and
customizing today's systems, applica�ons, and frameworks. Our solu�on-based books give you the
knowledge and power to customize the so�ware and technologies you're using to get the job done.
Packt books are more speci�c and less general than the IT books you have seen in the past. Our unique
business model allows us to bring you more focused informa�on, giving you more of what you need to
know, and less of what you don't.
Packt is a modern, yet unique publishing company, which focuses on producing quality, cu�ng-edge
books for communi�es of developers, administrators, and newbies alike. For more informa�on, please
visit our website:
Wri�ng for Packt
We welcome all inquiries from people who are interested in authoring. Book proposals should be sent
to
. If your book idea is s�ll at an early stage and you would like to discuss
it �rst before wri�ng a formal book proposal, contact us; one of our commissioning editors will get in
touch with you.
We're not just looking for published authors; if you have strong technical skills but no wri�ng
experience, our experienced editors can help you develop a wri�ng career, or simply get some
addi�onal reward for your exper�se.
XNA 4.0 Game Development by
Example: Beginner's Guide – Visual
Basic Edi�on
ISBN: 978-1-84969-240-3 Paperback: 424 pages
Create your own exci�ng games with Visual Basic and
Microso� XNA 4.0
Visual Basic edi�on of Kurt Jaegers' XNA 4.0 Game
Development by Example. The �rst book to target
Visual Basic developers who want to develop games
with the XNA framework
Dive head�rst into game crea�on with Visual Basic
and the XNA Framework
Four di�erent styles of games comprising a puzzler,
space shooter, mul�-axis shoot 'em up, and a jump-
and-run pla�ormer
C# 5 First Look
ISBN: 978-1-84968-676-1 Paperback: 138 pages
Write ultra responsive applica�on using the new
asynchronous features of C#
Learn about all the latest features of C#, including
the asynchronous programming capabili�es that
promise to make apps ultra-responsive
Examine how C# evolved over the years to be more
expressive, easier to write, and how those early
design decisions enabled future innova�ons
Explore the language’s bright future building
applica�ons for other pla�orms using the Mono
Framework
www.PacktPub.com
Unity 3.x Game Development
Essen�als
ISBN: 978-1-84969-144-4 Paperback:488 pages
BUild fully func�onal, professional 3D games with realis�c
environments, sound, dynamic e�ects,and more!
Kick start your game development, and build
ready-to-play 3D games with ease.
Understand key concepts in game design
including scrip�ng, physics, instan�a�on, par�cle
e�ects, and more.
Test & op�mize your game to perfec�on with
essen�al �ps-and-tricks.
Unity 3.x Scrip�ng
ISBN: 978-1-84969-230-4 Paperback: 292 pages
Write e�cient, reusable scripts to build custom characters,
game environments, and control enemy Al in your
Unity game
Make your characters interact with bu�ons and
program triggered ac�on sequences
Create custom characters and code dynamic objects
and players’ interac�on with them
Synchronize movement of character and
environmental objects
Add and control anima�ons to new and exis�ng
characters
www.PacktPub.com
Table of Contents
Table of Contents
Preface
Preface
Discovering Your Hidden Scrip�ng Skills
Chapter 1
Introducing the Building Blocks for Unity Scripts
Chapter 2
Ge�ng into the Details of Variables
Chapter 3
Ge�ng into the Details of Methods
Chapter 4
Chapter 5
Using Dot Syntax for Object Communica�on
Chapter 6
Crea�ng the Gameplay is Just a Part of the Game
Chapter 7
Developing the State Machine
Chapter 8
Start Building a Game and Get the Basic Structure Running
Chapter 9
Moving Around, Collisions, and Keeping Score
Chapter 10
Summarizing Your New Coding Skills
Chapter 11
Ini�al State Machine �les
Completed code �les for Chapters 9 and 10
Pop Quiz Answers

Приложенные файлы

  • pdf 11177529
    Размер файла: 5 MB Загрузок: 0

Добавить комментарий