Learning C# by Developing Games with Unity 3D Beginner's Guide - Terry Norton - E-Book

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

Terry Norton

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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!

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 307

Veröffentlichungsjahr: 2013

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning C# by Developing Games with Unity 3D Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Time for action – heading
What just happened?
Pop quiz – heading
Have a go hero – heading
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Discovering Your Hidden Scripting 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 documentation on the Internet
Reason 2 for choosing C# – flexibility to use Unity scripts and regular C# code files
Reason 3 for choosing C# – coding rules are specific
Maneuvering around Unity's documentation
Time for action – opening the Reference Manual documentation for the transform Component
What just happened?
Time for action – opening the scripting reference documentation for the transform component
What just happened?
Are we really supposed to know all that stuff?
What is all that information?
Working with C# script files
Time for action – create a C# script file
What just happened?
Introducing the MonoDevelop code editor
Syncing C# files between MonoDevelop and Unity
Time for action – opening LearningScript in MonoDevelop
What just happened?
Watching for a possible "gotcha" when creating script files in Unity
Fixing sync if it isn't working properly
Pop quiz – dealing with scripts
Summary
2. Introducing the Building Blocks for Unity Scripts
Using the term method instead of function
Understanding what a variable does in a script
Naming a variable
A variable name is just a substitute for a value
Time for action – creating a variable and seeing how it works
What just happened?
Time for action – changing the number 9 to a different number
What just happened?
Have a go hero – changing the value of myNumber
Using a method in a script
What is a method?
Time for action – learning how a method works
What's in this script file?
Method names are substitutes too
What just happened?
Have a go hero – changing the output of the method
Introducing the class
By using a little Unity magic, a script becomes a Component
A more technical look at the magic
Even more Unity magic
Have a go hero – finding Start and Update in the Scripting Reference
Components communicating using the Dot Syntax
What's with the dots?
Pop quiz – knowing the C# building blocks
Summary
3. Getting into the Details of Variables
Writing C# statements properly
Understanding Component properties in Unity's Inspector
Variables become Component properties
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 action – making a variable private
What just happened?
Naming your variables properly
Begin variable names with lowercase
Using multi-word variable names
Have a go hero – viewing multi-word variables in the Inspector panel
Declaring a variable and its type
The most common built-in variable types
Time for action – assigning values while declaring the variable
What just happened?
Where you declare a variable is important
Variable scope – determining where a variable can be used
Pop quiz – knowing how to declare a variable
Summary
4. Getting into the Details of Methods
Ending a method definition using curly braces
Using methods in a script
Naming methods properly
Begin method names with an uppercase letter
Using multi-word names for a method
Parentheses are part of the method name
Defining a method properly
The minimum requirements for defining a method
Understanding parentheses – why are they there?
Time for action – adding code between the parentheses
What just happened?
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 action – returning a value from AddTwoNumbers()
What just happened?
Have a go hero – add two more numbers together
Calling a method is a logic detour
Using Unity's Update and Start methods
The Start method is called one time
The Update method is called over and over and over…
Pop quiz – understanding method operation
Summary
5. Making Decisions in Code
Testing conditions with an if statement
Testing if conditions are true or false
Time for action – create a couple of if statements
What just happened?
Using the NOT operator to change the condition
Checking many conditions in an if statement
Time for action – create if statements with more than one condition to check
What just happened?
Have a go hero – change the value assigned to temperature
Have a go hero – change theBearMadeBigPottyInTheWoods to false
Using an if-else statement to execute alternate code
Time for action – add "else" to the if statement
What just happened?
Pop quiz – understanding if statements
Making decisions based on user input
Storing data in an array, a List, or a Dictionary
Storing items in an array
Storing items in a List
Time for action – create a List of pony names
What just happened?
Have a go hero – add another pony to the List
Storing items in a Dictionary
Time for action – create a dictionary of pony names and keys
What just happened?
Using a Collection Initializer to add items to a List or Dictionary
Time for action – adding ponies using a Collection Initializer
What just happened?
Pop quiz – understanding an array and a List
Looping though lists to make decisions
Using the foreach loop
Time for action – using foreach loops to retrieve data
What just happened?
Using the for loop
Time for action – selecting a pony from a List using a for loop
What just happened?
Using the while loop
Time for action – finding data and breakout of the while loop
What just happened?
Have a go hero – changing the pony name being searched
Summary
6. Using Dot Syntax for Object Communication
Using Dot Syntax is like addressing a letter
Simplifying the dots in Dot Syntax
Using access modifiers 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 action – accessing a variable in the current Component
What just happened?
Accessing another Component on the current GameObject
Time for action – communicating with another Component on the Main Camera
What just happened?
Accessing other GameObjects and their Components
Time for action – creating two GameObjects and a new script
What just happened?
On LearningScript:
Have a go hero – creating and using a new variable named capsuleComp
Accessing GameObjects using drag-and-drop versus writing code
Time for action – trying drag-and-drop to assign a GameObject
What just happened?
Pop quiz – understanding communication between objects
Summary
7. Creating 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
Benefits of by using a State Machine
Following the State Machine logic flow
Delegating game control to a State
Switching to another State when called to do so
Keeping track of the active State
Creating Components objects and C# objects
Unity creates Components behind the scenes
Instantiate a class to create an object
Time for action – creating a script and a class
What just happened?
Time for action – instantiating the BeginState class
What just happened?
Specifying a file's location with a namespace declaration
Locating code files with a using statement
Introducing the C# interface
The State Machine and the interface guarantee
Time for action – implementing an interface
What just happened?
Have a go hero – adding another method to the interface
Pop quiz – using a State Machine for game control
Summary
8. Developing the State Machine
Creating four State classes
Time for action – modifying BeginState and add three more States
What just happened?
Setting up the StateManager controller
Studying an example of inheritance
Enter the IStateBase interface again
Time for action – modify StateManager
What just happened?
Summarizing the code flow
Adding another State
Time for action – modifying PlayState to add another State
What just happened?
Adding OnGUI to the StateManager class
Time for action – adding OnGUI to StateManager
What just happened?
Changing the active State and controlling the Scene
Time for action – adding GameObjects and a button to the Scene
What just happened?
Pausing the game Scene
Time for action – adding code to pause the game Scene
What just happened?
Changing the State using a timer
Time for action – creating a timer in BeginState
What just happened?
Have a go hero – changing the State switching order
Changing Scenes
Time for action – setting up another Scene
What just happened?
Changing Scenes destroys the existing GameObjects
Keeping GameManager between scenes
Time for action – adding the Awake method to StateManager
What just happened?
Changing the Scenes
Time for action – adding the code to change the Scenes
What just happened?
Pop quiz – understanding State Machine operation
Verifying the code of your classes
Summary
9. Start Building a Game and Get the Basic Structure Running
Easing into Unity's scripting documentation
Reading the Unity Reference Manual first
Finding code examples in the Scripting Reference as needed
Setup the State Machine and add a Player GameObject
Time for action – setting up nine States and three Scenes
In Unity
In MonoDevelop
What just happened?
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 action - adding a Player GameObject
What just happened?
Storing game data in its own script
Time for action – creating a GameData script
What just happened?
Understanding images as textures in Unity
Using splash screens between game levels
Displaying the splash screens
Have a go hero – adjusting the button size and placement
Controlling the Player GameObject
Time for action – rotating Player in SetupState
What just happened?
Adding the Player Color option
Time for action – changing the color using GUI buttons
What just happened?
Adding the Lives option for Player
Time for action – setting the Lives for Player
What just happened?
Have a go hero – changing the setup spin speed
Pop quiz – understanding GameObjects
Summary
10. Moving Around, Collisions, and Keeping Score
Visualizing the completed game
Switching to the first play State and playable scene
Loading Scene1 using code
Adding cameras for different viewing options
Time for action – setting up two additional cameras in the scene
What just happened?
Attaching scripts to the new cameras
Time for actioning – attach the LookAtPlayer camera script
What just happened?
Time for action – attaching the FollowingPlayer camera script
What just happened?
Moving the Player using Rigidbody physics
Time for action – adding a Rigidbody to the Player
What just happened?
Keeping score during the game
Initializing 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 action – creating a good and bad prefab
What just happened?
Scoring for the win
Losing when Player crashes
Shooting projectiles at the orbs
Time for action – creating the EnergyPulse prefab
What just happened?
Shooting a single-shot EnergyPulse
Shooting rapid-fire EnergyPulses
The EnergyPulse is fired
Controlling EnergyPulse objects
Have a go hero – analyzing the code for the second level of play
Pop quiz – knowing which Unity methods to call
Summary
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 pattern choice
Using the State Machine at the GameObject level
Pulling all the little C# pieces together
Learning more after this book
Visit my favorite website for C#
Visit my favorite websites for Unity coding:
Summary
A. Initial State Machine files
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
B. Completed code files 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
C. Pop Quiz Answers
Chapter 1, Discovering Your Hidden Scripting Skills
Pop quiz – dealing with scripts
Chapter 2, Introducing the Building Blocks for Unity Scripts
Pop quiz – knowing C# building blocks
Chapter 3, Getting into the Details of Variables
Pop quiz – knowing how to declare a variable
Chapter 4, Getting into the Details of Methods
Pop quiz – understanding method operation
Chapter 5, Making Decisions in Code
Pop quiz – understanding if statements
Pop quiz – understanding an array and a List
Chapter 6, Using Dot Syntax for Object Communication
Pop quiz – understanding communication between objects
Chapter 7, Creating the Gameplay is Just a Part of the Game
Pop quiz – using a State Machine for game control
Chapter 8, Developing the State Machine
Pop quiz – understanding State Machine operation
Chapter 9, Start Building a Game and Get the Basic Structure Running
Pop quiz – understanding GameObjects
Chapter 10, Moving Around, Collisions, and Keeping Score
Pop quiz – knowing which Unity methods to call
Index

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

Learning C# by Developing Games 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 transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information 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 information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2013

Production Reference: 1190913

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK..

ISBN 978-1-84969-658-6

www.packtpub.com

Cover Image by Artie Ng (<[email protected]>)

Credits

Author

Terry Norton

Reviewers

Gaurav Garg

Kristian Hedeholm

Acquisition Editor

James Jones

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

Production Coordinator

Aditi Gajjar

Cover Work

Aditi Gajjar

About the Author

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.

I want to thank my daughter Emily Norton, the artist in the family, for helping me with the graphic's design.

About the Reviewers

Gaurav Garg was born in Delhi. He is a Computer Applications 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. After this, he learnt that passion is not the only thing for geting success; experience matters a lot. Then he joined Isis Design Service as a game programmer, where he published a few iOS titles 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 titles 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 articles was published in Game Coder Magazine. The article was on Unity3D. You can download the article from his personal website, http://gauravgarg.com/.

I would like to thanks my parents who taught me the value of hard work and an education.

I need to thanks my friends, particularly Manjith and Vibhash, who always took the time 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.

Kristian Hedeholm studied Computer Science at Aarhus University and now works as a game programmer at Serious Games Interactive in Copenhagen, Denmark. Since Kristian joined the game industry back in 2009, he has worked on a couple of released casual games. In addition to this, he is also the chairman of an association called Young Game Developers, which aims to spread information about game development among children and teenagers. In the future, Kristian will use his "computer mind" to develop artificial intelligence and dynamic difficulty adjustment systems for computer games.

When Kristian isn't developing games, teaching others to develop games, or playing games himself, he thinks about them a lot!

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

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 creating a game or interactive 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 artist coming to Unity, creating the visual aspects of a game is a breeze, but writing 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 find 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 sections 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!"

What this book covers

Chapter 1, Discovering Your Hidden Scripting Skills, explains that the very first thing you need to do is overcome your perceived fear of writing scripts. You'll see that writing scripts is very similar to many of your daily routines. We also have a first look at Unity's scripting documentation. Finally, we see how to create a C# script file in Unity.

Chapter 2, Introducing the Building Blocks for Unity Scripts, explains that there are two primary building blocks for writing 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, communication between GameObjects is discussed by introducing Dot Syntax.

Chapter 3, Getting 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 properties which appear in the Unity Inspector panel.

Chapter 4, Getting into the Details of Methods, explains how methods perform the actions that take place on GameObjects. We see how to create and use methods in detail. We also look into two of Unity's most often used methods, the Start() method and the Update() method.

Chapter 5, Making Decisions in Code, 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 6, Using Dot Syntax for Object Communication, shows us what Dot Syntax actually is, a simple address format to retrieve information or send information to other Components.

Chapter 7, Creating 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 functional 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 8, 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 multi-level game and how to deal with GameObjects when changing to another scene.

Chapter 9, Start Building a Game and Get the Basic Structure Running, teaches us how to access and use Unity's Scripting Reference and the Reference Manual for the features we want. Then we begin creating a multi-level game using the state machine and three scenes. A Player GameObject is added and we learn how to control it.

Chapter 10, 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 shooting projectiles at enemy objects, and see how to win or lose the game. Ultimately, we see how all the separate pieces of code come together and work together.

Chapter 11, 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 benefits of incorporating a state machine into your Unity projects. Finally, I present my favorite sources for further learning.

Appendix A, Initial State machine files, shows the initial code for the classes needed for changing States in our game. These State Machine classes are the starting point for organizing and adding game code.

Appendix B, Completed code files for Chapters 9 and 10, shows all the class and script files used for playing our completed game.

What you need for this book

You need the free version of Unity located at http://unity3d.com/unity/download/. The MonoDevelop code editor is included in the Unity installation.

Your computer will need to meet the minimum requirements for Unity as specified at http://unity3d.com/unity/system-requirements.html.

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) capabilities. Any card made since 2004 should work.

Who this book is for

If you don't know anything about programming in general, writing code, writing 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.

Conventions

In this book, you will find several headings appearing frequently.

To give clear instructions of how to complete a procedure or task, we use:

Reader feedback

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 titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

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.

Downloading the example code

You can download the example code files for all Packt books you have purchased 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.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find 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 frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection 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 location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

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 scriptsSee why we should use C# instead of UnityScriptIntroduce Unity's documentation for scriptingLearn 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