Home Game Development Learning C# by Developing Games with Unity 3D Beginner's Guide

Learning C# by Developing Games with Unity 3D Beginner's Guide

By Terry Norton
books-svg-icon Book
eBook $32.99 $22.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $32.99 $22.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Discovering Your Hidden Scripting Skills
About this book
For the absolute beginner to any concept of programming, writing a script can appear to be an impossible hurdle to overcome. The truth is, there are only three simple concepts to understand: 1) having some type of information; 2) using the information; and 3) communicating the information. Each of these concepts is very simple and extremely important. These three concepts are combined to access the feature set provided by Unity. "Learning C# by Developing Games with Unity 3D Beginner's Guide" assumes that you know nothing about programming concepts. First you will learn the absolute basics of programming using everyday examples that you already know. As you progress through the book, you will find that C# is not a foreign language after all, because you already know the words. With a few keywords and using substitution, before you know it, you'll be thinking in code. The book starts by explaining in simple terms the three concepts you need for writing C# code and scripts: 1) variables to hold information; 2) methods (functions) to use the information; and 3) Dot Syntax to communicate the information where it's needed. The book builds on these concepts to open up the world of C# coding and Unity scripting. You will use this new power to access the features provided in Unity's Scripting Reference. The first half of this book is devoted to the code writing beginner. The concepts of variables, methods, Dot Syntax, and decision processing are fully explained. Since C# is an actual programming language, we take advantage of this to develop a State Machine to help control and organize each phase of a Unity project. Once the basic programming concepts are established and we have some State Machine organization, the features and power of Unity are accessed using the Scripting Reference. If you're looking to learn C# for Unity then this is the book that offers everything you need and more - so discover what C# offers today and see your work come to life as complete games!
Publication date:
September 2013
Publisher
Packt
Pages
292
ISBN
9781849696586

 

Chapter 1. Discovering Your Hidden Scripting Skills

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.

 

Prerequisite knowledge for using this book


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.

 

Dealing with scriptphobia


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.

Teaching behaviors to GameObjects

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:

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 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?

 

Choosing to use C# instead of UnityScript


So why choose C# to create this code? This maybe after-the-fact information for you if you've already acquired this book and chosen to use C#, but these are valuable points to know anyway:

Reason 1 for choosing C# – vast amount of documentation on the Internet

Have a look at the following bullet list, it will help you understand the reason for choosing C#:

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

  • UnityScript is just a scripting language designed specifically for Unity. It's similar to JavaScript, yet it isn't. You may be able to search for JavaScript solutions on the web, but the code may or may not work within the confines of Unity without modification, if at all.

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

Reason 2 for choosing C# – flexibility to use Unity scripts and regular C# code files

  • Any C# files you have in your Unity Project folder, that are not Unity scripts, are accessible without the need of attach them to GameObjects.

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

Reason 3 for choosing C# – coding rules are specific

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

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

Note

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.

 

Time for action – opening the Reference Manual documentation for the transform Component


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.

  1. In the Hierarchy tab, select the Main Camera.

  2. Click on the book icon for the Transform.

What just happened?

The web browser opened the Reference Manual showing information about Transform.

 

Time for action – opening the scripting reference documentation for the transform component


From the Reference Manual, we'll now open the Scripting Reference documentation for the Transform Component.

  1. Click the link Switch to Scripting in the upper right-hand side of the browser window as shown in the following screenshot:

What just happened?

The Transform page in the Scripting Reference opens in the web browser as shown in the following screenshot:

Are we really supposed to know all that stuff?

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.

What is all that information?

The previous screenshot shows a description 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!"

 

Working with C# script files


Until you learn some basic programming concepts, it's too early to study how scripts work, but we still need to know how to create one.

There are several ways to create a script file using Unity:

  • In the menu navigate to Assets | Create | C# Script

    Or

  • In the Project tab navigate to Create | C# Script

    Or

  • In the Project tab right-click , from the pop-up menu navigate to Create | C# Script

    Note

    From now on, when I tell you to create a C# script, please use which ever method you prefer.

 

Time for action – create a C# script file


As our Unity project progresses, we will have several folders to organize and store all of our C# files.

  1. Create a new Unity project and name it as State Machine.

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

  3. Right-click on the Code folder and a create a folder named Scripts.

  4. In the Scripts folder, create a C# Script.

  5. Immediately rename NewBehaviourScript to LearningScript.

What just happened?

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 LearningScript.cs.

Introducing the MonoDevelop code editor

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.

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

 

Time for action – opening LearningScript in MonoDevelop


Unity will synchronize with MonoDevelop the first time you tell Unity to open a file for editing. The simplest way to do this is just double-click on LearningScript in the Scripts folder.

  1. In Unity's Project tab, double-click on LearningScript:

What just happened?

MonoDevelop started with LearningScript open, ready to edit.

Watching for a possible "gotcha" when creating script files in Unity

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.

Fixing sync if it isn't working properly

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.

Pop quiz – dealing with scripts

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?

 

Summary


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.

About the Author
  • Terry Norton

    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 until 2004 that programming peaked his interest. He began writing articles for OS/2 Magazine to teach C++ programming. Unfortunately, damaging his left hand in a snowblower accident in 2005 ended his writing for a couple years. IBM abandoned OS/2, so Terry bought his first Apple computer in early 2006. He tried a few times to learn Objective-C, but work and family always seemed to sidetrack his efforts. It wasn't until about 2010 when he discovered Unity and the need to write scripts, that he finally made some progress into the programming world. He began writing an online tutorial for UnityScript titled UnityScript for Noobs. It was a basic tutorial for beginners made available just before Unite 2011. Since then, Terry has been learning C# for writing scripts for Unity. Packt Publishing noticed UnityScript for Noobs and asked if he would be interested in writing a book about learning UnityScript. He declined. He felt that C# was a better language, and his heart just wasn't into UnityScript any longer. Two weeks later, Packt offered him the opportunity to write a book about learning C# for Unity. He jumped on it.

    Browse publications by this author
Latest Reviews (4 reviews total)
Received in time for the course to begin
Libro è risultato utile. Ottimo riferimento.
Learning C# by Developing Games with Unity 3D Beginner's Guide
Unlock this book and the full library FREE for 7 days
Start now