Unity Scripting: Working with Variables

Published December 03, 2018 by Micael DaGraca and Greg Lukosek, posted by Packt
Do you see issues with this article? Let us know.
Advertisement

What is a variable? Technically, it's a tiny section of your computer's memory that will hold any information that you put there. While a game is running, it keeps track of where the information is stored, the value kept there, and the type of that value. However, for this chapter, all you need to know is how a variable works. It's very simple.

This tutorial has been taken from Learning C# 7 By Developing Games with Unity 2017 - Third Edition and published by Packt.

What's usually in a mailbox, besides air? Well usually there's nothing, but occasionally there is something in it. Sometimes, there are letters, bills, a spider, and so on. The point is that what is in a mailbox can vary. Therefore, let's call each mailbox a variable.

In the game development world, some simple examples of variables might be:

  • playerName
  • playerScore
  • highestScore

How to name a variable

Using the example of the mailbox, if I asked you to see what is in the mailbox, the first thing you'd ask is, "Which one?" If I say in the Smith mailbox, the brown mailbox, or the round mailbox, you'll know exactly which mailbox to open to retrieve what is inside it. Similarly, in scripts you have to give your variables a unique name. Then I can ask you what's in the variable named myNumber, or whatever cool name you might use.

Let's see how this is represented in our code. The first thing we need to do is create a new script in Unity, all the fun and magic starts here from these first steps:

  1. In the Unity project panel, under the Assets tab, we are going to right–click the empty space:

01NcHTnyRUcTYl6omRMswDqZIZehL0U0n0wztX_g

  1. Then we go to the Create menu and select the C# Script option

  2. A new file was created and it is ready to be renamed; this is very important and we need to always give a name to this file. For now, we can call it variableScript (the name we gave to this file doesn't interfere with the content on it, so we can we choose any name we want):

EpR9I5W8Yz4G-AbJqxlNbel3k-2ZmCr3yrzAy_qC

 

0ui0eickGUw6dvXdvVQwUhK4jSJK4AXuO0eLWUoX

 

  1. Then we double-click the script file that we have just created.

  2. The MonoDevelop program will open with the script ready to edit:

c8c-mb1-RRtATxnt-07ndb_r-73U5XKThARIj_TZ

 

  1. Make sure that the name that appears after public class is exactly the same name that you assigned inside Unity (in this example, we gave the name variableScript). In case we don't rename the script file right away when it gets created, Unity will automatically assign the NewBehaviourScript name:

CUyijldJ_9rj11OPsqQyrjm0Gx_p0QyMVw-dxkis

 

  1. Now we are ready to create our first variable, we are going to name it myNumber. Make sure that your script looks identical to the following screenshot (for now, don't be concerned about the details of how to write this):

brlJ7sOXxFrYGKhl_gr3sIf-ZGjCx55Sp0nhrQ6k

 

  1. Then save the file

Note: When you name variables, try to come up with a name that most accurately describes what value your variable contains. Avoid generic names such as name, speed, and score. Instead, name them playerName, carSpeed, and opponentScore, respectively.

A variable name is just a substitute for a value

As you write a script and create a variable, you are simply creating a placeholder or a substitute for the actual information that you want to use. Look at the following simple math equation: 2 + 9 = 11.

Simple enough! Now try the following equation: 11 + myNumber = ???. There is no answer to this. 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 equation. What's the value in myNumber? The value is 9. So now the equation looks normal: 11 + 9 = 20.

The myNumber variable is nothing more than a named placeholder that can store some data (information). So, wherever you would like the number 9 to appear in your script, just write myNumber and the number 9 will be substituted.

We can test this on the script that we had previously created, so let's do it:

  1. We start by selecting the script that we have created and then we double–click it to open inside MonoDevelop:

zjHaBSSSuM2qEBYnK4GFLhpKtp0weqAOykPZZAwF

 

  1. Now we create a new variable called total and we don't need to assign any number to it because we want this variable to show us the result of our:

NpqTvgroIcob9inuEIx1aoRaJJ7cR-pI_kb6M67i

  1. After the void Start () function, we are going to write the math equation total = 2 + myNumber:

1P_cwJFoOEqfg795L5Z9EScU7gHvvVA5w8M6eLHW

 

  1. Save the file, go back to the Unity program, and drag and drop the script file on top of the Main Cameraobject:

q8-Qako-UH3ukoydpVHPCpuGQv9x-mEgUXoKe-By
 

  1. Click Play and take a look at the Total variable:

pbvyMPZZQG_VUiMv3UKoAJO5nqdOMPo2TLGJprLX

 

Although this example might seem silly at first, variables can store all kinds of data that is much more complex than a simple number. This is just a simple example that shows you how a variable works. We will definitely look at more complex variable types at later stages. Remember, slow, steady progress, baby steps!

Creating a variable and seeing how it works

Now using a different method, we are going to develop a script that shows us the result on the Unity console. Once again, don't be concerned about the details of how to write this; we are going to explain everything in more detail in future chapters. Just make sure that your script is the same as the script shown in the next screenshot:

  1. In the Unity Project panel, double-click variableScript. The MonoDevelop window should open automatically on variableScript.cs.

  2. In MonoDevelop, erase what we have done before and write the lines 7, 12, and 14, as shown in the following screenshot:

N4wlPpsA-JtWByzcIrUSDpi9a1kwyEMEivUZTKar

 

  1. Save the file.

Note: The best way to save your script is by using a shortcut. If you are using a Mac, use command + S, and on Windows use Ctrl + S. We will be saving a new version of the script every time some changes are made to it, so it is a good idea to use a shortcut instead of saving through the Filemenu.

We have added a few lines to our script. Before we check whether it works or what it actually does, let's go through line 7:


public int myNumber = 9;

In simple words, this line declares a new number type variable named myNumber and assigns a value of 9 to it. We don't want to worry about theory too much now and want to write more code, right? Agreed, but we do need to remember a few things first.

Declaration

To create a new variable, we first need to declare it by saying what type of variable it is, and as we explored before, a variable type represents the content. This means that the content for the myNumber variable is a number. The keyword for whole number variables in C# is int and for different types of content, we assign a different keyword. We also have to give our variable a name; myNumber is fine for now. You can use any name you want, as long as it does not contain spaces or special characters.

Assignment

We have created our variable, and now we are giving it a value. To assign a value, we use the equals sign followed by the value. In this case, it is 9. To close the line, use a semicolon; this is always necessary. The program reads our script one line of code at a time, and by using the semicolon we are telling the program that the line of code ends there.

Click play!

Quite an exciting moment! Go back from MonoDevelop to Unity and click the Play button. Unity should print out two lines on the Console tab, looking like this:

cnWHCq_z_epV5qhSCz7M_HWLz2qAuty7kEACPSp9

Unity executed the code in the variableScript component on the GameObject just after you clicked Play. We can see two lines printed on the Console window. We wrote a piece of code asking Unity to print these two values the Console window. Let's look again at lines 11 and 13. Everything inside the brackets in the Debug.Log function will be printed to the Unity Console. It can be a number, text, or even an equation:

LxeauSmYu7JCdcylX_bTCsuU9bloUBL1SC1G_7kf

So, line 11 is asking, "Hey Unity, print the result of 2 + 9 on the console!" Line 14 is using the myNumber variable's value directly and adding it to the number 11.

Thus, the point of this exercise is to demonstrate that you can store and use whatever values you want using variables, and use their names directly to perform operations.

How to change variables

Since myNumber is a variable, the value that it stores can vary. If we change what is stored in it, the answer to the equation will also change. Follow these steps:

  1. Stop Unity by pressing the Stop button and change 9 to 19 in the Unity Inspector tab

  2. Notice that when you restart the game, the answer will be 30

I bet you have noticed the public keyword at the very beginning of the line that declares the myNumber variable. Let me explain what it means. It's called an access modifier. We use these to specify the accessibility of a variable. The public keyword means that the variable can be seen by code outside our script. Look again at the Unity Inspector tab. You can see the value of myNumber there because it is public. The private keyword, however, means that the variable can be accessed only by code in the same class.

Note: Private variables are not visible in the Unity Inspector tab. If you wish to control or view them, make them public.

Watch for a possible gotcha when using public variables

Unity gives us great flexibility with editing or reading public variables in the Inspector tab. You will be using public variables most of the time. Now, I want to make you aware of something that might give you a headache sometimes.

Note: All public variable values are overridden by the Unity Inspector tab.

Let's look back at line 6; we had assigned our variable a value of 9. This value will be copied to the Unity Inspector. From now on, the value from Inspector is taken into account and not the value in the script, even if you change it. Therefore, be careful as this is very easy to forget.

In the Inspector panel, try changing the value of myNumber to some other value, even a negative value. Notice the change in the answer in the Console tab.

 

This tutorial is an excerpt from "Learning C# 7 By Developing Games with Unity 2017 - Third Edition" by Micael DaGraca, Greg Lukosek and published by Packt.

Get the complete eBook for just $10 (limited period offer).


Thanks for reading! Learn more on the Packt Hub: Creating interactive Unity character animations and avatars [Tutorial]

Cancel Save
0 Likes 0 Comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!

This tutorial is an excerpt from "Learning C# 7 By Developing Games with Unity 2017 - Third Edition" by Micael DaGraca, Greg Lukosek and published by Packt.

Advertisement

Other Tutorials by Packt

21911 views
Advertisement