C# Variables — Learning with Unity
Objective: Understand the role of variables in coding, using Unity examples
If you’re familiar with coding, then variables are a concept you already know. Instead, if you are approaching this world you may find this practical guide useful.
I’m going to show, in the easiest way, what variables are, how we manipulate them in C# and how we can use this knowledge in game developing with Unity.
Well, let’s put it in a simple way: when coding, you need something to store information, so you can retrieve it later for any purpose you may have. Every coding language has this concept, borrowed from math: the variable. The name is self-explanatory, since this is an entity which is storing an information, which can be modified (although some languages allow to define also constants). From now on, we will refer to the stored information as value.
When defining a variable, the computer will allocate some memory, to be written with the variable value. This memory will be identified (mostly by the computer) with an address. So a variable can be considered as a virtual box, containing a value. The computer finds the box by means of its address, the programmer uses its name.
The act of “defining” a variable in code is called declaration, let’s now declare a variable in C#. For this purpose I created a new Unity project and I’m going to work with C# script created within the editor.
Inside the class, named Variables101, I declared two variables. Let’s see what we can learn:
- The declaration starts with an access modifier. Here we have public, meaning that the variable is visible and accessible outside the class, and private, the variable is accessible only within the class.
- Data Type follows, defining what type of value is stored. Each type represent something different (string stands for a series of characters, int is an integer number…) and requires a different amount of memory. For a list of value types and their size, refer to official Microsoft documentation.
- Name. Well, it’s the name of the variable, the one the programmer and the compiler will use to identify it.
- Initialization. This one is optional, as you can see the first variable is only declared, the secondo has also an assigned value. When not assigned, the compiler will give the variable a default value, according to the type (0 for numbers, false for bools…).
Notice that camelCase format was used: all names made with more than on word are written with the first lowercase letter and every word then starts with an uppercase letter. It is not mandatory but it’s a best practice.
Also notice that the private variable starts with an underscore, again not mandatory but a best practice: in this way, among manymanymany variables programmers can easily find the private ones
Data types such as int, float (floating point decimal), bool etc. are value types and have a different behaviour from the so called reference type such as classes (like our script itself). Classes allow to define the blueprint of more or less complex objects (stored in a reference variable), which are made of other variables and also methods. Apart from this huge difference, let’s remember:
When passing a value type variable as a method parameter, just its value will be passed. Manipulating that value from inside the method, will not affect the original value.
When passing a reference type variable as a method parameter, its address will be passed. Manipulating the variable from inside the method, will affect the original value.
Reference type variables can be initialize by means of their constructor, a particular method called with the new keyword that allocates memory for the object and, optionally, initialize its inner variables.
Let’s go back to Unity now. And declare some other variables, but this time of reference type. I declared a private GameObject, which represent the generic object or entity in our game (could be a player, and enemy, the sun, a weapon… even a simple container for other game objects), a public Camera, a private AudioClip (also annotated with SerializeField) and a Vector2, initialized through its constructor.
When assigning decimal number values, always remember to put the correct real literal suffix, corresponding to the data type (f for float, m for decimal etc.)
As I said before, private and public are access modifiers, private variables can be accessed only within the class, public ones also from outside. What does it mean in terms of Unity? If you drag the script onto a game object in the Hierarchy view and attach the script as a component, the Inspector will show all the variables which are accessible and lets you also manipulate them (set values).
After attaching he script Variables101.cs to the MainCamera, that’s the result.
You can see that Player Name and Camera Obj are visible, being public, but also Audio, the private one!!
Audio variable was annotated with SerializeField, a useful tool that lets you use private variables and their restricted access through code, while giving Unity the possibility to access them.
Now let’s try and use variables for game developing! Create a Player script and attach it to the MainCamera.
That’s a simple player stat, like the ones in an RPG. Notice the use of comma instead of the semicolon, to separate variables of the same type. Honestly, I don’t like this too much, but I have to admit that it is quite cleaner when I have many SerializeField variables. String are always to be written between quotes.
Time to mess around with this variables: let’s write a method that applies a damage of a certain value, may a random one (good ol’ D&D).
Using the static method Random.RandomRange and passing two integers (min and max) we’re going to get a random integer between min and max-1.
Now apply the damage. Let’s say a classic 1d6. The operator -= means that we are assigning to the variable a new value which is the old one minus the right side of the operator. It can also be coded as
_hp = _hp-GetRandomDamage(6);
And to finish this, let’s put some log around, so we can have a clue of what is happening through the console.
I messed around a bit: I put some logs through the method Debug.Log() which take a string as a parameter. While handling string, the sum operator + becomes an append operator, which creates a unique string by attaching one to another. When using the sum operator between strings and numbers, the number will be considered a string, the literal expression of the number (11 becomes “11”).
Let’s now launch the game:
You can get the code from my GitHub repository!