If there’s one thing I have learned in my time as a professional artist, it’s the value of having a tool that can be used to make a wide range of marks and textures depending on how it is used. Individual marks form the overall structure of a painting, and each kind of mark has its own purpose in serving that structure. The canvas doesn’t know what it will show the viewer until the artist has defined a subject using marks from a tool. The same is true for scripts and variables.
Just as the artist adds definition to a figure, I need to be ready to define some terms that our script can understand. The tool for the job is called a variable. A variable is a sort of container for holding information about your game. If I need my game to count ammunition or health, conditionally gate progress, or know the PC’s custom name I’m gonna need variables.
Let’s start by looking at the anatomy of a variable in C#.
The first thing every variable needs is to know what parts of the program can access it. We can call it “public,” in which case any part of the program can see it and assign it a value. Or we can call it “private,” and then only elements of the script where the variable is defined can interact with it.
Next is the variable’s data type. There are several different types, some unique to Unity. We’ll cover the most common here, but if you want to know more check the Unity documentation on the subject.
Some common data types are:
* Float — A number with or without decimal values, like 0.5 or 13.25.
* Integer — A number without any decimal value, like 3 or 200.
* Boolean — A value that can only be either true or false. Commonly used in logic or in toggles.
* String — A piece of text, like a name or a message.
Some common Unity specific data types are:
* GameObject — A specific object in the scene, such as an enemy.
* Animator — An animation controller, used to trigger animations via script.
* Transform — An objects position, scale, and rotation, usually along 2 or three axes like (0, 0, 0).
The final portion is optional: we can assign a value to the variable at the beginning of the script. If we skip this step, then the variable will be assumed null until it is assigned a value later in the script. The value must match the data type.
It’s easy to see with such a wide array of potential uses how important variables are. And we’re just scratching the surface.
In the next article we’ll go over the importance of writing pseudo code.