Learning C# by Developing Games with Unity 5.x - Second Edition

4.6 (12 reviews total)
By Greg Lukosek
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Discovering Your Hidden Scripting Skills and Getting Your Environment Ready

About this book

Unity is a cross-platform game engine that is used to develop 2D and 3D video games. Unity 5 is the latest version, released in March 2015, and adds a real-time global illumination to the games, and its powerful new features help to improve a game’s efficiency.

This book will get you started with programming behaviors in C# so you can create 2D games in Unity. You will begin by installing Unity and learning about its features, followed by creating a C# script. We will then deal with topics such as unity scripting for you to understand how codes work so you can create and use C# variables and methods. Moving forward, you will find out how to create, store, and retrieve data from collection of objects.

You will also develop an understanding of loops and their use, and you’ll perform object-oriented programming. This will help you to turn your idea into a ready-to-code project and set up a Unity project for production. Finally, you will discover how to create the GameManager class to manage the game play loop, generate game levels, and develop a simple UI for the game.

By the end of this book, you will have mastered the art of applying C# in Unity.

Publication date:
March 2016
Publisher
Packt
Pages
230
ISBN
9781785287596

 

Chapter 1. Discovering Your Hidden Scripting Skills and Getting Your Environment Ready

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:

  • Deal with preconceived fears and concepts about scripts

  • Prepare the Unity environment for efficient coding

  • Introduce Unity's documentation for scripting

  • Explain how Unity and the MonoDevelop editor work together

  • Create 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.

 

Prerequisite knowledge to use this book


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. 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. I will help you, however, to prepare the Unity layout for efficient scripting.

 

Dealing with scriptphobia


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 on 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 on 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 everyday that are just like 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 habits. Think about this for a moment: do you have to consciously think about these routines that you do everyday? Probably not. After you do them over and over, they become automatic.

The point is that you do things everyday 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 of 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 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 everyday. I'm sure you will have many Ah-Ha moments as you learn and overcome your unjustified fears and beliefs.

 

Downloading Unity


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 obsolete for you, skip this part.

The best place to download your Unity copy from is, of course, Unity's official website: http://unity3d.com/unity/download.

In this book, we will be covering Unity Version 5.0 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.

Obtaining a free license

The easiest way to obtain a Unity license is by simply launching Unity for the first time. The following steps will guide you to do so:

  1. Unity will present the Activate your Unity license window. Click on OK, as shown here:

  2. Fill in your details so that Unity Technologies can send you your Unity free license code:

  3. You should receive a verification e-mail with a confirm email button. Once you have clicked on it, you should be able to log in to Unity.

You are now all set with the latest version of Unity and a free license!

 

Teaching behavior to GameObjects


You have Unity because you want to make a game or something interactive. 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?

Using Unity's documentation

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 that 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. This is worth remembering if there are Internet connectivity issues:

  • Through the Help menu next to the component name. This will work only for Unity's built-in, standard components.

Let's open Scripting Reference now and search for a GameObject. 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 fastest access to relevant information, use Search scripting... in the top-right corner, as shown here:

Do I need to know all that?

Actually, no. 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

  • Renderer

 

C# documentation – where to find it? Do I need it at all?


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.

The Unity community – asking others for help

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 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, "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.

 

Working with C# script files


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:

  1. In the menu, navigate to Assets | Create | C# Script.

  2. In the Project tab, navigate to Create | C# Script.

  3. Right-click in the Project tab, and from the pop-up menu, navigate to Create | 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.

Lots of files can create a mess

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.

Why does my Project tab look different?

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 his/her 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.

Note

The Console tab shows messages, warnings, errors, or debug output from your game. You can define your own messages to be sent to the console.

 

Creating a C# script file


We are now ready to create a new C# file in our learning project:

  1. Create a new Unity project and name it Learning Project.

  2. Right-click on the Project tab and create a folder named Scripts.

  3. Right-click on the Scripts folder, as shown in the following screenshot, and create a C# script:

  4. Immediately rename NewBehaviourScript to LearningScript.

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.

 

Introducing the MonoDevelop code editor


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.

Syncing C# files between MonoDevelop and 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.

Opening LearningScript in MonoDevelop

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. 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 – highlighted in blue

The namespace is simply an organization construct. It helps organize parts of code. Don't worry too much about them 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.

The class definition – highlighted in green

A class definition starts with the class keyword, followed by a class name and an optional base class name, followed by a class body enclosed in curly braces:

public class LearningScript : MonoBehaviour {

}

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.

  • Hover the mouse pointer on the SUPPORT tab at the top.

  • Click on Code Downloads & Errata.

  • Enter the name of the book in the Search box.

  • Select the book for which you're looking to download the code files.

  • Choose from the drop-down menu where you purchased this book from.

  • Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

Again, don't worry about this too much. Let's not introduce too much theory. All that we need to focus on now is how the class definition looks.

Note

The code contained inside your class is called class body. By default, Unity creates two functions inside a class body.

Watching for possible gotchas while creating script files in Unity

Notice line 4 in the preceding 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.

Fixing synchronization if it isn't working properly

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.

Adding our script to GameObject

We have created the LearningScript class. Its code is saved in the file in the Project/Assets folder. To include an instance of this class in our project, we will add it as a component to an empty GameObject.

Lets 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 GameObject. Let's talk about the simplest one:

  1. Select your newly created GameObject.

  2. Drag and drop the Script file from the Project tab to the empty space underneath the Transform 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.

 

Instance? What is it?


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 this up; they are, in fact, two different things. GameObject is a 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.

 

Summary


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—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 by introducing the building blocks for Unity scripts—by taking an introductory look at the building blocks of programming—for which 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 everyday.

About the Author

  • Greg Lukosek

    Greg Lukosek was born and raised in the Upper Silesia region of Poland. When he was about 8 years old, his amazing parents bought him and his brother a Commodore C64. That was when his love of programming started. He would spend hours writing simple basic code, and when he couldn't write it on the computer directly, he used a notepad.

    Greg completed his mechanical engineering diploma at ZSTiO Meritum— Siemianowice Slaskie, Poland. He has learned all his programming skills through determination and hard work at home.

    Greg met the love of his life, Kasia, in 2003, which changed his life forever. They both moved to London in search of adventure and decided to stay there.

    He started work as a 3D artist and drifted away from programming for some years. Deep inside, he still felt the urge to come back to game programming. During his career as a 3D artist, he discovered Unity and adopted it for an interactive visualizations project. At that very moment, he started programming again.

    His love for programming overcomes his love for 3D graphics. Greg ditched his 3D artist career and came back to writing code professionally. He is now doing what he really wanted to do since he was 8 years old—developing games.

    These days, Greg lives in a little town called Sandy in the UK with Kasia and their son, Adam.

    Browse publications by this author

Latest Reviews

(12 reviews total)
I love the constant sales that happen, I love how frequent they happen, and I love how many resources you get with the PDF files. The books are easy to access and they are well detailed.
Love the book at a great price.
Good, but I would love if the book contains at least an appendix to talk a bit about UNITY game engine before delving into programming.
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial