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 documentation for scripting
Learn how Unity and the MonoDevelop editor work together
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 scripting 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 operation is required. I 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, how to work with GameObjects in your Scene, and how to locate Components and view their Properties in the 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 fantastic, 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 scripting tutorials, maybe even copy and paste some scripts to get some action 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 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 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 routines", or maybe as habits. Think for a moment, do you have to consciously think about these routines you do every day? Probably not. After you do them over and over, they become automatic.
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 scripting your whole life. You just never had to write down the steps, for your daily routines, on a piece of paper before doing them. You could write the steps down if you really wanted to, but it takes too much time 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 writing down the steps. Not for yourself but for the world you're creating 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 scripting 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 scripting 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 unjustified fears and beliefs.
You have Unity because you want to make a game or something interactive. You've filled 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 instructions so that your GameObjects can be smarter.
Here's a quote from the Unity Manual:
Notice 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 Scripting 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 little code to tie into these behaviors. Did you catch that? Unity has already created the behaviors, all we have to do is supply a little bit of C# code to apply these behaviors to our GameObjects. Now really, how difficult can it be since Unity has already done most of the programming?
C# is a well known and a heavily used programming language developed by Microsoft for creating Windows application and web-based applications. If you ever need to know anything about C#, simply do a search on the Internet.
Why start off learning a limited scripting language, specific only to Unity, when you can use C#, a true programming language, and find information everywhere?
Who knows, once you see how easy C# is, maybe you might decide to develop for Windows or the Web some day. You'll already have the basics of C#.
Once you learn C#, you'll pretty much know UnityScript, too.
The State Machine project we will create for this book makes use of C# code files that are not attached to any GameObject.
I'm not saying you can't create a State Machine by using UnityScript. It's just so much easier with C#. Every UnityScript file has to be attached to a GameObject to work and be accessible to other scripts. C# overcomes this necessity.
As you write code, Unity will catch coding errors immediately. Learning a subject is always easier when the rules are specific, and not some fuzzy "you can if you want to" kind of logic.
UnityScript is not a strictly-typed language. You have the potential to write code that is not valid, but Unity won't catch the errors until 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.
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. For specific coding details and examples we'll use the Scripting Reference.
When you look at the code examples in the Scripting 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 Scripting Reference such as displaying some output to Unity's Console. 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 documentation from within Unity, we'll use the Main Camera to demonstrate. Every GameObject in a Scene has a Transform Component, so we'll look at the documentation for Transform in the Reference Manual and the Scripting Reference. Getting to the information is pretty easy. Click on the tiny book icon with the question mark.
In the Hierarchy tab, select the Main Camera.
Click on the book icon for the Transform.
Click the link Switch to Scripting in the upper right-hand side of the browser window as shown in the following screenshot:
Actually, no. The whole reason for why the Scripting Reference exist is so we can look for information as we need it. Which will actually happen us to remember the code we do over and over, just like our other daily routines and habits.
There are several ways to create a script file using Unity:
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
Codefolder and a create a folder named
Scriptsfolder, create a
We created one of the
Code subfolders, named
Scripts, that we will be using to organize our C# files. This folder will contain all of our Unity script files. Later we will create other C# file folders.
We also used Unity to create a C# script file named
Unity uses an external editor to edit its C# scripts. Even though Unity 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 and Unity synchronized with each other. This means that if you add, delete, or change a script file in one application, the other application will see the changes automatically.
In Unity's Project tab, double-click on
Notice line 4 in the previous screenshot:
public class LearningScript : MonoBehaviour
The class name
LearningScript is the same as the file name
LearningScript.cs. This is a requirement. You probably don't know what a class is yet, that's ok. Just remember that the file name 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 renamed. 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 would be this:
public class NewBehaviourScript : MonoBehaviour
This can easily be fixed in MonoDevelop by changing
NewBehaviourScript on line 4 to the same name as the filename, 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.
Q1. As a beginner, what's the biggest obstacle to be overcome to be able to write C# code?
Q2. The Scripting Reference supplies example code and a short description of what the code does. What do you use to get full detailed descriptions of Unity's Components and features?
Q3. The Scripting Reference is a large document. How much it should you know before attempting to write any scripts?
Q4. When creating a script file in Unity, when is the best time to name the script file?
This chapter tried to put you at ease about writing scripts for Unity. You do have the ability to write down instructions which is all a script is, 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 saw how to easily bring up Unity's documentation. Finally we had a look at the MonoDevelop editor. None of this was complicated. In fact, you probably use apps all the time that do similar things. Bottom line, there's nothing to fear here.
Alright, let's start off 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 often, perhaps every day.