Variables in Unity and C#
One of the first concepts you learn about in programming is the use of variables — and rightly so, I just gave myself a headache trying to imagine programming without them! In fact the simple demonstration above required 9 different variables to work.
So what is a variable? The best way to think of a variable is as a container that holds a value. The variable stays constant however the value it contains can be changed. Even if a variable contains no value it can still be useful.
Before a variable can be used, it must first be declared. Each language has unique ways to accomplish this. With C#, there are 3 required parts to a variable declaration and an optional 4th.
public int value = 10;
Firstly, there is the access modifier which defines the level of access that other areas of your project have to your variable. The most common ones are public, private and protected.
Public — All access, any script in your project can gain access.
Private — No access, no script outside the one you declare a private variable in can access it.
Protected — Limited access, only inheriting members can gain access. More on inheritance in another article.
Following the access modifier, we have the data type — there are 4 main types used frequently in Unity and C#, these are —
int — Short for integer, this is a whole number value.
float — A decimal number value.
bool — True or false value.
string — A ‘string’ of characters, these can include letters, numbers and special characters and the values are always encompassed by “quotation marks”.
After the data type we need to give the variable a name, something that defines it’s purpose or usage so as not to be confused with something else. Call a spade, a spade as the saying goes…
The optional part of the declaration is the value, this can be omitted in the declaration and will instead just be given a default value. For int and float data types, the default is zero, a bool’s default is false and a string’s default value is nothing or ‘null’.
When we declare variables, we also have an array of attributes we can specify for each variable.
In this example, I have grouped the variables together under the heading ‘Details’. While normally, a private variable doesn’t get seen in the inspector, if we use the [SerializeField] attribute, we can see and adjust the value of the variable in the inspector (notice the lack of age variable in there…). We can also provide a tooltip to accompany our variable.
Variables are the flexible backbone of all programming, they can be referenced and changed at will to suit our needs as developers. There is no end to the value of using variables, other than your imagination!
Hmm…maybe I should have had the background change colour with each bounce too…