yazik.info Programming Learning C# Programming With Unity3d Pdf


Wednesday, June 12, 2019

It was a basic tutorial for beginners made available just before Unite Since then, Terry has been learning C# for wriing scripts for Unity. Packt Publishing. Designed to give you enough familiarity in a programming language to be immediately productive, Learning C# Programming with Unity 3D provides the basics of programming and brings you quickly up to speed. Organized into easy-to-follow lessons, the book covers how C# is used to. with Unity 3D Beginner's Guide He began wriƟng arƟcles for OS/2 Magazine to teach C++ programming. Unfortunately, damaging his left Since then, Terry has been learning C# for wriƟng scripts for Unity. Packt Publishing Did you know that Packt offers eBook versions of every book published, with PDF and ePub.

Learning C# Programming With Unity3d Pdf

Language:English, Spanish, Hindi
Published (Last):15.01.2016
ePub File Size:20.46 MB
PDF File Size:15.42 MB
Distribution:Free* [*Register to download]
Uploaded by: CORINNA

Download Best Book Learning C# Programming with Unity 3D, PDF FILE Download Learning C# Programming with Unity 3D Free Collection. International Standard Book Number (eBook - PDF) lot of time learning how the entire system internals work—building block based on C# programming, that would offer extensibility in any direction a developer. with Unity 3D Beginner's Guide. Learn the peaked his interest. He began writing articles for OS/2 Magazine to teach C++ programming. Since then, Terry has been learning C# for writing scripts for Unity. your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub.

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: 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 operaion is required. I will only be covering the parts of the Unity interface that are related to wriing 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 Properies 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 fantasic, 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 scriping tutorials, maybe even copy and paste some scripts to get some acion 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! Is that what you have? The fear that you cannot write down instrucions in a coherent manner?

1st Edition

You may believe you have this alicion, but you don't. You only think you do. The basics of wriing 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 rouines", or maybe as habits. Think for a moment, do you have to consciously think about these rouines you do every day? Probably not. Ater you do them over and over, they become automaic. Who created these steps you follow? More than likely you did, which means you've been scriping your whole life. You just never had to write down the steps, for your daily rouines, on a piece of paper before doing them.

You could write the steps down if you really wanted to, but it takes too much ime 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 wriing down the steps. Not for yourself but for the world you're creaing 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 scriping is too hard to learn.

Learning C# Programming With Unity 3D By Alex Okita[AKD].pdf

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 scriping 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 unjusiied fears and beliefs. Teaching behaviors to GameObjects You have Unity because you want to make a game or something interacive. You've illed 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 instrucions 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 atached to them Unity allows you to create your own Components using scripts.

Noice 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 Scriping 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 litle code to ie into these behaviors. Did you catch that? Unity has already created the behaviors, all we have to do is supply a litle bit of C code to apply these behaviors to our GameObjects. Now really, how diicult can it be since Unity has already done most of the programming? This maybe ater-the-fact informaion 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: If you ever need to know anything about C , simply do a search on the Internet.

It's similar to JavaScript, yet it isn't. You may be able to search for JavaScript soluions on the web, but the code may or may not work within the conines of Unity without modiicaion, if at all. You'll already have the basics of C. It's just so much easier with C. Every UnityScript ile has to be atached to a GameObject to work and be accessible to other scripts. C overcomes this necessity. What does this means to you? Learning a subject is always easier when the rules are speciic, and not some fuzzy "you can if you want to" kind of logic.

You have the potenial to write code that is not valid, but Unity won't catch the errors unil you press Play. Maneuvering around Unity's documentation When we begin wriing scripts, we will be looking at Unity's documentaion quite oten, so it's beneicial to know how to access the informaion we need. For an overview of a topic we'll use the Reference Manual.

For speciic coding details and examples we'll use the Scriping Reference. When you look at the code examples in the Scriping 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 Scriping 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 documentaion from within Unity, we'll use the Main Camera to demonstrate. Geing to the informaion is prety easy. Click on the iny book icon with the quesion mark. In the Hierarchy tab, select the Main Camera. Click on the book icon for the Transform. The web browser opened the Reference Manual showing informaion about Transform.

Time for action — opening the scripting reference documentation for the transform component From the Reference Manual, we'll now open the Scriping Reference documentaion for the Transform Component. Click the link Switch to Scriping in the upper right-hand side of the browser window as shown in the following screenshot: The Transform page in the Scriping 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 Scriping Reference exist is so we can look for informaion as we need it. Which will actually happen us to remember the code we do over and over, just like our other daily rouines and habits. What is all that information? The previous screenshot shows a descripion 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! There are several ways to create a script ile using Unity: Time for action — create a C script ile As our Unity project progresses, we will have several folders to organize and store all of our C iles. Create a new Unity project and name it as State Machine.

Right-click on in the Project tab and create a folder named Code. Right-click on the Code folder and a create a folder named Scripts. In the Scripts folder, create a C Script. We created one of the Code subfolders, named Scripts, that we will be using to organize our C iles. This folder will contain all of our Unity script iles. Later we will create other C ile folders. We also used Unity to create a C script ile named LearningScript.

Even though Unity can create a basic starter C script for us, we sill have to edit the script using the MonoDevelop code editor that's included with Unity. This means that if you add, delete, or change a script ile in one applicaion, the other applicaion will see the changes automaically. The simplest way to do this is just double-click on LearningScript in the Scripts folder.

In Unity's Project tab, double-click on LearningScript: MonoDevelop started with LearningScript open, ready to edit. This is a requirement. You probably don't know what a class is yet, that's ok. Just remember that the ile name and the class name must be the same.

When you create a C script ile in Unity, the ilename, 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 ilename and the class name won't match. The ilename would change, but line 4 would be this: MonoBehaviour This can easily be ixed in MonoDevelop by changing NewBehaviourScript on line 4 to the same name as the ilename, 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: 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? The Scriping Reference supplies example code and a short descripion of what the code does. What do you use to get full detailed descripions of Unity's Components and features?

The Scriping Reference is a large document. How much it should you know before atemping to write any scripts? When creaing a script ile in Unity, when is the best ime to name the script ile? You do have the ability to write down instrucions which is all a script is, a sequence of instrucions. We saw how simple it is to create a new script ile.

You probably create iles on your computer all the ime. We saw how to easily bring up Unity's documentaion. Finally we had a look at the MonoDevelop editor. None of this was complicated.

In fact, you probably use apps all the ime that do similar things. Botom line, there's nothing to fear here. Alright, let's start of Chapter 2, Introducing the Building Blocks for Unity Scripts by having an introductory look at the building blocks of programming we'll be using: Don't let these terms scare you. The concepts behind each one of these are similar to things you do oten, perhaps every day. These parts are variables and methods.

Therefore, understanding these critical parts is a prerequisite for learning any of the other features of C.

Being as critical as they are, they are very simple concepts to understand. Using these variable and method foundation pieces, we'll be introduced to the C building blocks used to create Unity scripts. For those people who get sweaty palms just thinking of the word script, wipe your hands and relax. In this chapter, I'm going to use terms that are already familiar to you to introduce the building blocks of programming. The following are the concepts introduced in this chapter: The words funcion and method truly mean the same thing in Unity.

They do the same thing. It makes sense to learn the correct terminology for C. The authors of the Scriping Reference probably should have used the word method instead of funcion in all documentaion.

From now on I'm going to use the words method or methods in this book. When I refer to the funcions shown in the Scriping Reference, I'm going to use the word method instead, just to be consistent throughout this book.

Understanding what a variable does in a script What is a variable? Technically, it's a iny secion of your computer's memory that will hold any informaion you put there. While a game runs, it keeps track of where the informaion is stored, the value kept there, and the type of the value. However, for this chapter, all you need to know is how a variable works in a script.

It's very simple. Well, usually there's nothing but occasionally there is something in it. Someimes there's money a paycheck , bills, a picture from aunt Mabel, a spider, and so on. The point is what's in a mailbox can vary. Therefore, let's call each mailbox a variable instead.

Naming a variable Using the picture of the country mailboxes, if I asked you to see what is in the mailbox, the irst thing you'd ask is which one? If I said in the Smith mailbox, or the brown mailbox, or the round mailbox, you'd know exactly which mailbox to open to retrieve what is inside.

Similarly, in scripts, you have to name your variables with a unique name. Then I can ask you what's in the variable named myNumber, or whatever cool name you might use. A variable name is just a substitute for a value As you write a script and make a variable, you are simply creaing a placeholder or a subsitute for the actual informaion you want to use.

Look at the following simple math equaion: Now try the following equaion: There is no answer to this yet. You can't add a number and a word. Going back to the mailbox analogy, write the number 9 on a piece of paper. Put it in the mailbox named myNumber. Now you can solve the equaion. What's the value in myNumber? The value is 9. So now the equaion looks normal: So anywhere you would like the number 9 to appear in your script, just write myNumber, and the number 9 will be subsituted.

Although this example might seem silly at irst, variables can store all kinds of data that is much more complex than a simple number. This is just a simple example to show you how a variable works. Don't be concerned about the details of how to write this, just make sure your script is the same as the script shown in the next screenshot. In the Unity Project panel, double-click on LearningScript. In MonoDevelop, write the lines 6, 11, and 13 from the next screenshot.

Save the ile. To make this script work, it has to be atached to a GameObject. This will do nicely since this script doesn't afect the Main Camera in any way. The script simply runs by virtue of it being atached to a GameObject. Drag LearningScript onto the Main Camera. Select Main Camera so that it appears in the Inspector panel. Verify whether LearningScript is atached. Open the Unity Console panel to view the output of the script.

Click on Play. In the following Console panel is the result of our equaions. As you can see, the equaion on line 13 worked by subsituing the number 9 for the myNumber variable: Time for action — changing the number 9 to a different number Since myNumber is a variable, the value it stores can vary.

If we change what is stored in it, the answer to the equaion will change too. Follow the ensuing steps: Stop the game and change 9 to Noice that when you restart the game, the answer will be You learned that a variable works by simple process of subsituion. There's nothing more to it than that. We didn't get into the details of the wording used to create myNumber, or the types of variables you can create, but that wasn't the intent.

This was just to show you how a variable works. It just holds data so you can use that data elsewhere in your script. We'll get into the iner details of variables in Chapter 3, Variables in Detail. Have a go hero — changing the value of myNumber In the Inspector panel, try changing the value of myNumber to some other value, even a negaive value. Noice the change in answer in the Console.

Using a method in a script Methods are where the acion is and where the tasks are performed. Great, that's really nice to know but what is a method? What is a method? When we write a script, we are making lines of code that the computer is going to execute, one line at a ime. As we write our code, there will be things we want our game to execute more than once.

For example, we can write a code that adds two numbers. Suppose our game needs to add the two numbers together a hundred diferent imes during the game. So you say, "Wow, I have to write the same code a hundred imes that adds two numbers together.

There has to be a beter way. You just have to write the code to add two numbers once, and then give this chunk of code a name, such as AddTwoNumbers. Now, every ime our game needs to add two numbers, don't write the code over and over, just call the AddTwoNumbers method.

Time for action — learning how a method works We're going to edit LearningScript again. In the following screenshot, there are a few lines of code that look strange. We are not going to get into the details of what they mean in this chapter. We will discuss that in Chapter 4, Geing into the Details of Methods.

Right now, I am just showing you a method's basic structure and how it works: In MonoDevelop, select LearningScript for ediing. Edit the ile so that it looks exactly like the following screenshot.

What's in this script ile? In the previous screenshot, lines 6 and 7 will look familiar to you; they are variables just as you learned in the previous secion. There are two of them this ime. These variables store the numbers that are going to be added.

Line 16 may look very strange to you. Don't concern yourself right now with how this works. Line 17 is where the AddTwoNumbers method gets called into acion. In fact, that's exactly how to describe it. This line of code calls the method. Lines 20, 21, 22, and 23 make up the AddTwoNumbers method. Don't be concerned about the code details yet. I just want you to understand how calling a method works. Method names are substitutes too You learned that a variable is a subsitute for the value it actually contains.

Well, a method is no diferent. Take a look at line 20 from the previous screenshot: Like a variable, AddTwoNumbers is nothing more than a named placeholder in the memory, but this ime it stores some lines of code instead. So anywhere we would like to use the code of this method in our script, just write AddTwoNumbers , and the code will be subsituted. Line 21 has an opening curly-brace and line 23 has a closing curly-brace. Everything between the two curly-braces is the code that is executed when this method is called in our script.

Look at line 17 from the previous screenshot: This means that the code between the curly-braces is executed. It's like having all of the code of a method right there on line Of course, this AddTwoNumbers method only has one line of code to execute, but a method could have many lines of code.

Line 22 is the acion part of this method, the part between the curly-braces. This line of code is adding the two variables together and displaying the answer to the Unity Console. Then, follow the ensuing steps: Go back to Unity and have the Console panel showing. Now click on Play. Oh no! Nothing happened! Actually, as you sit there looking at the blank Console panel, the script is running perfectly, just as we programmed it. Press it now. And there you go!

The following screenshot shows you the result of adding two variables together that contain the numbers 2 and 9: When you do this, line 17 executes which calls the AddTwoNumbers method. This allows the code block of the method, line 23, to add the the values stored in the variables number1 and number2. Have a go hero — changing the output of the method While Unity is in the Play mode, select the Main Camera so its Components show in the Inspector.

Unity : Developing Your First Game with Unity and C#

In the Inspector panel, locate Learning Script and its two variables. Change the values, currently 2 and 9, to diferent values. You will see the result of the new addiion in the Console. You just learned how a method works to allow a speciic block of code to to be called to perform a task.

We didn't get into any of the wording details of methods here, this was just to show you fundamentally how they work. We'll get into the iner details of methods in Chapter 4, Geing into the Details of Methods. Introducing the class The class plays a major role in Unity. In fact, what Unity does with a class a litle piece of magic when Unity creates Components.

You just learned about variables and methods. These two items are the building blocks used to build Unity scripts. The term script is used everywhere in discussions and documents. Look it up in the dicionary and it can be generally described as writen text. Sure enough, that's what we have. However, since we aren't just wriing a screenplay or passing a note to someone, we need to learn the actual terms used in programming.

Unity calls the code it creates a C script. However, people like me have to teach you some basic programming skills and tell you that a script is really a class. In the previous secion about methods, we created a class script called LearningScript.

It contained a couple of variables and a method. The main concept or idea of a class is that it's a container of data, stored in variables, and methods that process that data in some fashion. Because I don't have to constantly write class script , I will be using the word script most of the ime.

However, I will also be using class when geing more speciic with C.

Just remember that a script is a class that is atached to a GameObject. These classes will not be atached to any GameObjects, so I won't be calling them scripts. By using a little Unity magic, a script becomes a Component While working in Unity, we wear the following two hats: When we put our Scriping hat on, our terminology changes as follows: Wave the magic wand — ZAP — the script ile is now called a Component, and the public variables of the script are now the properies you can see and change in the Inspector panel.

A more technical look at the magic A script is like a blueprint or a writen descripion. In other words, it's just a single ile in a folder on our hard drive. We can see it right there in the Projects panel.

It can't do anything just siing there. When we tell Unity to atach it to a GameObject, we haven't created another copy of the ile, all we've done is tell Unity we want the behaviors described in our script to be a Component of the GameObject. When we click on the Play buton, Unity loads the GameObject into the computer's memory. Since the script is atached to a GameObject, Unity also has to make a place in the computer's memory to store a Component as part of the GameObject.

The Component has the capabiliies speciied in the script blueprint we created. The scripts inherit from MonoBehaviour. For beginners to Unity, studying C inheritance isn't a subject you need to learn in any great detail, but you do need to know that each Unity script uses inheritance.

We see the code in every script that will be atached to a GameObject. In LearningScript, the code is on line 4: MonoBehaviour The colon and the last word of that code means that the LearningScript class is inheriing behaviors from the MonoBehaviour class.

This simply means that the MonoBehaviour class is making few of its variables and methods available to the LearningScript class. It's no coincidence that the variables and methods inherited look just like some of the code we saw in the Unity Scriping Reference.

The following are the two inherited behaviors in the LearningScript: Line So the code you place in these methods gets executed automaically. Have a go hero — inding Start and Update in the Scripting Reference Try a search on the Scriping Reference for Start and Update to learn when each method is called by Unity and how oten. Also search for MonoBehaviour. This will show you that since our script inherits from MonoBehaviour, we are able to use the Start and Update methods.

Components communicating using the Dot Syntax Our script has variables to hold data, and our script has methods to allow tasks to be performed. I now want to introduce the concept of communicaing with other GameObjects and the Components they contain.

It's what makes interacion possible. We need to communicate with other Components or GameObjects to be able to use the variables and methods in other Components. When you look at the code writen by others, you'll see words with periods separaing them. What the heck is that?

It looks complicated, doesn't it. The following is an example from the Unity documentaion: That's called the Dot Syntax. The following is another example. It's the iciious address of my house: That's because I used the syntax grammar of C instead of the post oice.

However, I'll bet if you look closely, you can easily igure out how to ind my house. Pop quiz — knowing the C building blocks Q1.

What is the purpose of a variable in a script? What is the purpose of a method in a script? How does a script become a Component?

What is the purpose of Dot Syntax? Summary This chapter introduced you to the basic concepts of variables, methods, and Dot Syntax.

These building blocks are used to create scripts and classes. Understanding how these building blocks work is criical so you don't feel you're not geing it. We discovered that a variable name is a subsitute for the value it stores; a method name is a subsitute for a block of code; when a script or class is atached to a GameObject, it becomes a Component. With these concepts under your belt, we can proceed to learn the details of the sentence structure, the grammar, and the syntax used to work with variables, methods, and the Dot Syntax.

In the next chapter we will learn about the details of using variables. It's not the actual words that cause the problem because, for the most part, many of the words are the same words that we use in our everyday life.

C is not a foreign language. The main problem is that the words simply don't read like the typical sentences we are all used to.

You know how to say the words and you know how to spell the words. What you don't know is where and why you need to put them in that crazy looking grammar, that is, the syntax that makes up a C statement. In this chapter, we will learn some of the basic rules for writing a C statement. We will also be introduced to many of the words that C uses and the proper placement of these words in the C statements when we create our variables.

In this chapter we will cover the following topics: When you write a line of code, it's called a statement with a semi-colon used to end the statement. The reason a statement ends with a semi-colon is so that Unity knows when the statement ends. A period can't be used because they are used in the Dot Syntax. The code for a C statement does not have to be on a single line as shown in the following example: Whitespace and carriage returns are ignored, so if you really want to, you can write it as follows: However, there will be imes that you'll have to write long statements that will be longer than one line.

Unity won't care. It just needs to see the semi-colon at the end. Understanding Component properties in Unity's Inspector GameObjects have some Components that make them behave in a certain way.

For instance, select Main Camera and look at the Inspector panel. One of the Components is the Camera. Without that Component, it will cease being a camera. It would sill be a GameObject in your scene, just no longer a funcioning camera.

We just aren't supposed to edit the scripts that Unity wrote. This means that all the properies we see in Inspector are just variables of some type. They simply store data that will be used by some methods. Unity changes script and variable names slightly When we add our script to a GameObject, the name of our script shows up in the Inspector panel as a Component. Unity makes a couple of small changes. Unity added a space to separate the words of the name. Unity does this modiicaion to the variable names, too.

Noice that the variable number1 is shown as Number 1, and number2 as Number 2. Unity capitalizes the irst leter as well. These displayed changes improve readability in Inspector. Changing a property's value in the Inspector panel There are two situaions when you can modify a property value: This is great when you're experimening and want to see the results.

When you are in the Play mode, you will see that your changes take efect immediately in real ime. Write down any changes you want to keep because when you stop the Play mode, any changes you made will be lost. When you are in the development mode, changes you make to the property values will be saved by Unity. This means that if you quit Unity and restart it again, the changes will be retained. Of course you won't see the efect of your change unil you click on Play.

The changes you make to the property values in the Inspector panel do not modify your script. The only way your script can be changed is for you to edit it in the script editor MonoDevelop. The values shown in the Inspector panel override any values you had assigned in your script. Click on the Cog icon the gear on the far right of the Component script, and then select Reset as shown in the following screenshot: Displaying public variables in the Inspector panel I'm sure you're wondering what the word public means at the beginning of a variable statement: It will be visible as a property in the Inspector panel so that you can manipulate the value stored in the variable.

It also means it can be accessed from other scripts using the Dot Syntax.


Time for action — making a variable private Not all variables need to be public. If there's no need for a variable to be changed in the Inspector panel nor be accessed from other scripts, it doesn't make sense to cluter the Inspector panel with needless properies.

In LearningScript, perform the following steps: Change line 6 to the following: Change line 7 to the following: In Unity, select Main Camera. You will noice in the Inspector panel that both properies, Number 1 and Number 2 are gone.

It is now a private variable to store data. If you don't explicitly state whether a variable will be public or private, by default, the variable will implicitly be private. It is good coding pracice to explicitly state whether a variable will be public or private. So now when you click on Play, the script works exactly as it did before. You just can't manipulate the values manually in the Inspector panel anymore.

Naming your variables properly Always use meaningful names for storing your variables. If you don't do that, six months down the line, you will be sad. I'm going to exaggerate here a litle bit to make a point.

I will name a variable as shown in the following code: In other words, you know what it means by just reading the variable, and so ten years from now when you look at that name, you'll know exactly what it means. I know right now you'll understand it because you just wrote it, but six months down the line, ater wriing hundreds of other scripts for all sorts of diferent projects, you'll look at that and wonder what potty meant.

You'll have to read several lines of code you wrote to try to igure it out. You may look at the code and wonder who in their right mind would write such a terrible code. So take the ime to write a descripive code that even a stranger can look at and know what you mean. Believe me, in six months or probably less, you will be that stranger. Begin variable names with lowercase You should begin a variable name with lowercase because it helps to disinguish between a class name and a variable name in your code.

The Component names class names begin with a capital leter. For example, it's easy to know that Transform is a class, and transform is a variable.

There are of course excepions to this general rule, and every programmer has a preferred way to use lowercase, uppercase, and perhaps an underscore to begin a variable name. At the end, you will have to decide upon a naming convenion you like. If you read the Unity forums, there are some heated debates on naming variables.

In this book, I will show you my preferred way, but you can use whatever is more comfortable for you. Using multi-word variable names Let's use the same example again as follows: Since variable names can be only one word, begin the irst word with a lowercase, and then just capitalize the irst leter of each addiional word. It greatly helps to create descripive names and sill being able to read it.

There's a word for this called camelCasing.

C# Programming for Unity Game Development Specialization

Have a go hero — viewing multi-word variables in the Inspector panel I already menioned that for public variables, Unity's Inspector will separate each word and capitalize the irst word.

Go ahead, add the previous statement to LearningScript and see what Unity does with it in the Inspector panel. What does that mean? Well, before Unity can use a variable; we have to tell Unity about it irst. Ok then, what are we supposed to tell Unity about the variable? There are only three absolute requirements for declaring a variable and they are as follows: The third requirement of ending a statement with a semi-colon has been discussed. The irst requirement of specifying the type of data will be covered next.

The following is what we know about this bare minimum declaraion as far as Unity is concerned: Just these basic types are presented here so that you understand the concept of a variable being able to store only the type of the data you specify. The custom types of data that you will create later will be discussed in Chapter 7, Creaing the Gameplay is Just a Part of the Game in the discussion of Dot Syntax. The following chart shows the most common built-in types of data you will use in Unity: Type Contents of the variable int A simple integer, such as the number 3 float A number with a decimal, such as the number 3.

However, once you understand the most common types, you'll have no problem looking up the other built-in types if you ever need to use them. We know the minimum requirements to declare a variable. However, we can add more informaion to a declaraion to save our ime and coding.

We've already seen some examples in LearningScript of assigning values when the variable is being declared and now we'll see few more examples. Time for action — assigning values while declaring the variable Add some more variables to LearningScript using the types shown in the previous chart.

While declaring the variables, assign them values as shown in the following screenshot. See how they are presented in the Inspector panel. These are all public variables so they will appear in the Inspector panel: The following screenshot shows what Unity presents in the Inspector panel: The variables are displayed in the Inspector panel with the values already set.

Where you declare a variable is important You will be declaring and using variables in many places in a script.

Everybody, Always: Becoming Love in a World Full of Setbacks and Difficult People

The variables that I have shown you so far are called member variables. They are members of the LearningScript class, not declared within any method. These member variables are the only variables that have the opion of being displayed in the Inspector panel or being accessed by other scripts. So where in the class should the member variables be declared? This is another subject that can lead to heated discussions.

Personally, I declare them at the top of a class ile before any methods are declared so that I see them all in one place. Other people like to declare variables close to the point of irst use in a method.

We will also be creaing variables in methods.

These variables are called as local variables and are never displayed in the Unity's Inspector panel, nor can they be accessed by other scripts. This brings us to another programming concept called variable scope. Variable scope — determining where a variable can be used Variable scope is a fancy way of saying "Where in the script does a variable exist". The following screenshot explains you the scope of variables: You might have noiced that the rectangular blocks start and end with curly-braces.

Just like the AddTwoNumbers method in Chapter 2, Introducing the Building blocks for Unity Scripts, the code between the opening curly-brace and a closing curly-brace is called a code block. Absolutely anywhere in a code that you have an opening curly-brace, there will be a closing curly-brace to match. All the code between the two braces is a code block. You normally don't just create bare blocks of code with curly-braces like I did with Code Block 3.

Code blocks are usually part of other things such as if statements, looping statements, and methods. This example is just to demonstrate how the scope of a variable works, and where a variable exists and is useable.

The following is what you have: This variable exists in the code block that is labeled Code Block 3. If you try to use the variable block3 outside of Code Block 3, such as in Code Block 2 or Code Block 1, Unity will give you an error message saying that variable block3 doesn't exist.

The scope of the variable block3 is the code block deined by the curly-braces of lines 13 and Now let's look at the block1 variable: Line 6: This variable exists in the code block that is labeled Code Block 1.

This code block begins on line 5 and ends on line This means the variable block1 can be used everywhere, including Code Block 2 and Code Block 3 because, they are also within Code Block 1. The block1 variable is used in Code Block 2 on line 10, and in Code Block 3 on line The scope of the block1 variable is the code block deined by the curly-braces between lines 5 and Pop quiz — knowing how to declare a variable Q1. What is the proper way to name a variable? How do you make a variable appear in the Unity's Inspector panel?

Can all variables in a script show in the Inspector panel? Can a variable store any type of data? All the Component properies shown in the Inspector panel are member variables in the Component's class. Member variables can be shown in the Inspector panel, or accessed by other scripts when the variable is declared as public. The type of data a variable can store is speciied when it's declared. Finally, we learned that variable scope determines where it is allowed to be used.

Now that we've learned about variables, we're ready to learn the details of C methods that will use the variables we create — which is the topic of the next chapter. The scope is determined by the "opening" and "closing" curly braces.

The purpose of those curly braces is to act as a container for a block of executable code, a code block. In second chapter you saw that a method is a code block that can execute by just calling the method's name.

It's time to see the importance of code blocks and the variables used in them. A method defines a code block which begins and ends with curly braces. In this chapter we will cover the features of methods: A method deiniion has a diferent requirement.

A method deiniion ends with a code block between a pair of curly braces. DO NOT end a method deiniion with a semicolon.

If you do accidentally place a semicolon at the end, MonoDevelop will gladly remind you with an error message that you're not supposed to use a semicolon at the end of a method deiniion. Using methods in a script There are two reasons for using methods in a script: The irst purpose of a method is to work with the member variables of the class.

The member variables store data that's needed for a Component to give a GameObject its behavior. The whole reason for wriing a script is to make a GameObject do something interesing. A method is the place we make the behavior come to life. The second purpose of a method is to create code blocks that will be used over and over again. You don't want to be wriing the same code over and over. This should get you covered in the following areas: the very basics of coding, like variables, functions and classes, and how to use them.

What is scripting in Unity? Now, scripting in Unity is different from pure programming. Instead, you focus on the gameplay in your scripts. Unity runs in a big loop. For example, it reads through the lights, the meshes, what the behaviors are, and it processes all of this information for you. If you think about television, where, for example in North America, you have You direct Unity with the instructions that you write in your scripts, and Unity executes them frame after frame as fast as it can.

Achieving a high frame rate means not only your game will look more fluid, but your scripts will also be executed more often, making controls more responsive. What languages can you use in Unity?

A script must be attached to a GameObject in the scene in order to be called by Unity. Scripts are written in a special language that Unity can understand.

All the languages that Unity operates with are object-oriented scripting languages. Like any language, scripting languages have syntax, or parts of speech, and the primary parts are called variables, functions, and classes.

Starting with What do these do? Variables start with a lowercase letter. Functions are collections of code that compare and manipulate these variables.

Functions start with an uppercase letter. We organise code in functions so that they can be easily reused multiple times in different parts of the program. Classes are a way to structure code to wrap collections of variables and functions together to create a template that defines the properties of an object. Scripting is primarily comparing these objects and their current states and values.

Variables In Unity, the scripts start by laying out the tools that you need at the top, and this is usually by declaring variables. So, that means other people can access it and change its value. There are many reasons to choose between private or public. Private variables allow your code to be cleaner, since you know that the value of those variables can be changed only inside that class.

This makes debugging and maintaining the code easier. However, if you want objects to communicate between themselves you need some variables or functions to be public.

Another important aspect of variables is the type. A type defines what kind of value is the variable holding in memory, e. Unity needs to know what type of object it is so that it knows how to handle it.We will discuss that in Chapter 4, Geing into the Details of Methods. For example, it reads through the lights, the meshes, what the behaviors are, and it processes all of this information for you.

You will have to include an addiional call to AddTwoNumbers. There are only three absolute requirements for declaring a variable and they are as follows: For instance, select Main Camera and look at the Inspector panel. Each element is given an index number.