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 who can write computer code. The perception is that learning to write code takes great technical skills that are 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 that you may have of yourself by refocusing, one step at a time, on the knowledge that you already possess to write code and develop an awesome game from scratch.
In this chapter, we will cover the following topics:
- Dealing with preconceived fears and concepts about scripts
- Preparing the Unity environment for efficient coding
- Introducing Unity's documentation for scripting
- Explaining how Unity and the MonoDevelop editor work together
- Creating our first C# script
Let's begin our journey by eliminating any anxiety about writing scripts for Unity and become familiar with our scripting environment.
Great news if you are a beginner in scripting! 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 operation is required. We will only be covering the parts of the Unity interface that are related to writing C# code. I am assuming that you know your way around Unity's interface. I will help you, however, to prepare the Unity layout for efficient scripting.
You've got Unity up and running, studied the interface, and 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 do anything else that you can dream of. So you click Play
, and nothing happens. Well, darn it all anyway!
You've just learned a big lesson: all those fantastic, highly detailed GameObjects
are dumber than a hammer. They don't know anything, and they surely don't know how to do anything.
So, you proceed to read the Unity Forums
, study some scripting tutorials, and maybe even copy and paste some scripts to get some action going when you click Play
. That's great, but then you realize that 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.
You look at the code, your palms get sweaty, and you think to yourself, "I'll never be able to write scripts!" Perhaps you have scriptphobia: a fear of not being able to write instructions (I made that up). Is that what you have?
The fear that you cannot write down instructions in a coherent manner? You may believe you have this affliction, but you don't. You only think you do.
The basics of writing 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 bologna 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 everyday routines or maybe habits. Think about this for a moment: do you have to consciously think about the routines that you do every day? Probably not. After you do them over and over, they become automatic.
The point is that you do things every day following sequences of steps. Who created these steps that you follow? More than likely, you did, which means that you've been scripting your whole life.
You just never had to write down the steps for your daily routines on a piece of paper before you did them. You could write the steps down if you really wanted to, but it takes too much time and there's no need for it; however, you do in fact know how to. Well, guess what? To write scripts, you only have to make one small change, start writing down the steps, not for yourself but for the world that you're creating in Unity.
So as you can see, you are already familiar with the concept of dealing with scripts. Most beginners of Unity easily learn their way around the Unity interface, how to add assets, and working in the Scene and Hierarchy windows. Their primary fear and roadblock is their false belief that scripting is too hard to learn.
Relax! You now have this book. I am going to get really basic in the early chapters. Call them baby steps if you want, but you will see that scripting for Unity is similar to doing things that you are already doing every day. I'm sure you will have many Aha moments as you learn and overcome your unjustified fears and beliefs.
You have probably already installed and activated Unity. Where you should look for the latest Unity version and license might be obvious. However, I've noticed lots of questions online about where you can get Unity for free, and so I decided to cover this subject. If you feel that this step is unnecessary for you, skip this part.
The best place to download your Unity copy from is, of course, Unity's official website: https://store.unity.com/download?ref=personal.
In this book, we will be covering Unity Version 2017.1.1 and higher. We need to download the latest version of Unity and install it with all components ticked. It's a good idea to install Unity with the example project. The Unity Example project (the Angry Bots game) is there for us to play with, experiment, and learn.
Unity has a store where we can also download more example projects and start playing around with them. To access the store, you can do it online or directly from the Unity engine, so don't worry if you forgot to check the Unity Example project in the installation menu because you can download it at any time.
The easiest way to obtain a Unity license is by simply launching Unity for the first time. The following steps will guide you through it:
- Fill in your details so that Unity Technologies can send you your Unity free license code.
- Unity will present the
License management
window. Chose theUnity Personal
(free version). - You should receive a verification email with a
C
onfirm
button. Once you have clicked it, you should be able to log in to Unity.email
You are now all set with the latest version of Unity and a free license!
You have Unity because you want to make a game or something interactive, such as an AR or VR experience. You've filled your game with dumb GameObjects
. What you have to do now is be their teacher. You have to teach them everything that they need to know to live in this world of make–believe. This is the part where you have to write down instructions so that your GameObjects
can be smarter.
Here's a quote from the Unity Manual:
"The behavior of GameObjects is controlled by the Components that are attached to them... Unity allows you to create your own Components using scripts."
Notice the 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'll teach them the behaviors we want them to have. The best part is that Unity has provided a long list of all the behaviors that we can give to our GameObjects
. This list of behaviors is documented in the Scripting Reference
.
This means that we can pick and choose anything that we want a GameObject
to do from this list of behaviors. Unity has done all the hard work of programming all of these behaviors for you. All we need to do is use some code to tie into these behaviors. Did you catch that? Unity has already created the behaviors; all that we have to do is supply a bit of C# code to apply these behaviors to our GameObjects
. Now, how difficult can it really be since Unity has already done most of the programming?
When we begin writing scripts, we will be looking at Unity's documentation quite often, so it's beneficial to know how to access the information we need. For an overview of a topic, we'll use the Reference Manual, and for specific coding details and examples, we'll use the Scripting Reference
.
There are a number of ways to access the Unity documentation:
- Through the Unity website at http://docs.unity3d.com/ScriptReference/index.html.
- Through the
Help
menu on the top bar. In this way, you can access a local copy of Unity reference as we can see in the following image. This is worth remembering if there are internet connectivity issues:

- Let's open
Scripting Reference
now and search for aGameObject
:

- Through the
Help
menu next to the component name. This will work only for Unity's built-in, standard components.
This is the place where we can find scripting documentation, answers to our questions, and a lot of example code. You might feel a bit lost right now, but don't worry, this is quite normal. The Unity documentation is really easy to use. For the fastest access to relevant information, use Search scripting...
in the top–right corner, as shown here:

Note
The whole reason Scripting Reference
exists is so that we can look for information as we need it. This will actually make us remember the code that we write over and over, just like our other daily routines and habits. It is a very good idea to take a brief look through the most common Unity objects, such as GameObject, Transform, MonoBehaviour, and Renderer.
Another resource that we will be using is Microsoft's C# scripting documentation. We can access it at https://msdn.microsoft.com/en-us/library/67ef8sbd.aspx.
Let's not worry about it too much at the moment. We agreed to take baby steps, so bookmark this link in your web browser for now.
You are planning to become a game developer, or are using Unity for other interactive projects. During production, at some point, you will definitely need help from other developers. Unity has a very dedicated community of developers who are always keen to help each other.
When we encounter some hurdles, why not ask others? In most cases, there is someone like you out there with similar issues that have been resolved. A good place to talk about issues in your project is in the Unity Forums
. Go ahead and create a forum account now! Don't be shy; say "hello" to others! Unity Forums
are also the perfect place to read announcements about upcoming updates.
Use Unity Forums
to read about others' work, share your work, and connect with other developers at http://forum.unity3d.com/.
Use Unity Answers
to ask specific questions about issues that you have encountered. Remember to be very specific, try to describe the problem in detail, and don't ask general questions. For example, don't ask, "Why is my GameObject
not moving?" Instead, ask specifically, "GameObject
not moving when adding a rigid body force" and then describe the details. Posting your code under the question is also a very good idea.
Until you learn some basic concepts of programming, it's too early to study how scripts work, but you still need to know how to create one.
There are several ways of creating a script file using Unity:
- In the menu, navigate to
Assets
|Create
|C# Script
- In the Project tab, navigate to
Create
|C# Script
- Right-click on the
Project
tab, and from the pop–up menu, navigate toCreate
|C# Script
All of these ways create a .cs
file in the Unity Assets
folder. From now on, whenever I tell you to create a C# script, use whichever method you prefer.
We are now ready to create a new C# file in our learning project:
- Create a new Unity project and name it
Learning Project
- Right-click on the
Project
tab and create a folder namedScripts
- Right-click on the
Scripts
folder, as shown in the following screenshot, and create a C# script:

- Immediately rename
NewBehaviourScript
toLearningScript
We have created the Scripts
folder, which we will be using to organize our C# files. This folder will contain all of our Unity script files. We have also used Unity to create a C# script file named LearningScript.cs
.
Unity uses an external editor to edit its C# scripts. Even though it can create a basic starter C# script for us, we still have to edit the script using the MonoDevelop code editor that's included with Unity.
Since Unity and MonoDevelop are separate applications, Unity will keep MonoDevelop synchronized with itself. This means that if you add, delete, or change a script file in one application, the other application will reflect the changes automatically.
It is possible to also choose another code editor if we want to. For example, web developers can keep using their favorite editor if they choose to do so. If you feel more comfortable using another code editor, you can do it by following these steps:
- Go to the
Preferences
menu that can be found under theUnity
tab on Mac, or theEdit
tab on Windows - Select
External Tools
:

- Under the
External Script Editor
option, you can browse for the application that you want to use as the code editor:

Unity will synchronize with MonoDevelop the first time you tell it to open a file for editing. The simplest way to do this is by double-clicking on LearningScript
in the Scripts
folder (provided in the example project). If your project is empty, don't worry, you can create a new C# script that will contain the exact same information. To do it, you just need to right-click inside the Assets
tab and select Create
| C#Script
. It might take a few seconds for MonoDevelop to open and sync.
Our window should look like this:

MonoDevelop launched with LearningScript
open and ready to edit.
What we see now is a default C# script structure that Unity creates. It contains information on what namespaces are used in the script, the class definition, and two methods that Unity adds by default, as shown here:

The namespace is simply an organizational construct. It helps organize parts of code. Don't worry too much about it now. We won't need to create them anytime soon. All we will need to know for now is how many namespaces we are using in our script.
In our script, we can see these two lines:
using UnityEngine; using System.Collections;
The preceding two lines simply mean that our script will be using the UnityEngine
and System.Collections
namespaces, and we will have access to all parts of these libraries. These two namespaces are added to any new C# script by default, and we will use them in most of our cases.
Notice line4
in the following screenshot:

public class LearningScript : MonoBehaviour
The class name LearningScript
is the same as the filename LearningScript.cs
. This is a requirement. You probably don't know what a class is yet, but that's okay. Just remember that the filename and the class name must be the same.
When you create a C# script file in Unity, the filename in the Project
tab is in Edit
mode, ready to be changed. Please rename it right then and there. If you rename the script later, the filename and the class name won't match. The filename would change, but line 4
will be this:
public class NewBehaviourScript : MonoBehaviour
This can easily be fixed in MonoDevelop by changing NewBehaviourScript
in line 4
to the same name as the filename, but it's much simpler to do the renaming in Unity immediately.
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 them for whatever reason, do this. Right–click on Unity's Project
window and select Sync MonoDevelop Project
. MonoDevelop will resync with Unity.
We have created the LearningScript
class. Its code is saved in the file in the Project
/Scripts
folder. To include an instance of this class in our project, we will add it as a component to an empty GameObject
.
Let's create a new GameObject
. In the menu, navigate to GameObject
| Create Empty Child
, as shown here:

There are a number of ways of adding our LearningScript
component to the GameObject
. Let's talk about the simplest one:
- Select your newly created
GameObject
:

- Drag and drop the
Script
file from theProject
tab to the empty space underneath theTransform
component:

We can now see that our LearningScript
file has been added as a component to the GameObject
. This means that an instance of LearningScript
is active and ready to execute code.
As our Unity project progresses, we will have lots of different types of files in the Project
view. It's highly recommended that you keep a clean and simple folder structure in your project.
Let's keep our scripts in the Scripts
folder, textures in Textures
, and so on, so that it looks something like this:

From now on, let's not keep any loose files in the Assets
folder.
Unity allows us to customize the user interface. Everyone has their own favorite. I prefer a one–column layout Project
tab instead of Unity's default two–column layout. To change this, open the context menu in the top-right corner of the Project
tab, as shown in this screenshot:

When working in a team, you will notice that every team member has their own layout preference. A level designer may like to use a big Scene
tab. An animator will probably use the Animation
and Animator
tabs. For a programmer like you, all tabs are fairly important. However, the Console
tab is the one that you will use a lot while testing your code. I mostly prefer a layout divided into four columns from left to right, Scene
, and Console
, then Hierarchy
, then Project
, and finally Inspector
.
It looks like what is shown in the following screenshot:

Note
If you have trouble with moving tabs around, refer to the Customizing Your Workspace chapter in the Unity Manual.
Feel free to change the interface however you want. But try to keep the Console
tab visible all the time. We will use it a lot throughout the book. You can also save your custom layouts in the Layout
menu.
In object-oriented programming, an instance is simply a copy of the object. In this case, there is one copy of our LearningScript
file. We are using two terms here: GameObject
and Object. Do not mix these up, they are, in fact, two different things. GameObject
is an object in your Unity scene. It contains components such as Transform
or our newly created LearningScript
.
Object in programming means an instance of the script. Don't worry about the terminology too much at this stage. I am sure that the difference between these two will become much clearer soon.
This chapter tried to put you at ease with writing scripts for Unity. You do have the ability to write down instructions, which is all a script is, just a sequence of instructions. We saw how simple it is to create a new script file. You probably create files on your computer all the time. We also saw how to easily bring forth Unity's documentation. We created a channel to communicate with other developers. Finally, we took a look at the MonoDevelop editor. None of this was complicated. In fact, you probably use apps all the time that do similar things. The bottom line: there's nothing to fear here.
In Chapter 2, Introducing the Building Blocks for Unity Scripts, we will start off introducing the building blocks for Unity scripts by taking an introductory look at the building blocks of programming. For this, we'll be using variables, methods, dot syntax, and classes. Don't let these terms scare you. The concepts behind each one of these are similar to things that you do often, perhaps every day.