Variables in code are a pretty valuable tool to add flexibility and global support throughout your scripts.
Like with mathematical statements, you can write out all the values needed to solve the equation. However, as equations become more complex, you may want a way to shorthand name for common values in order to solve the statement more easily. You may have seen these values back in school as “x” or “y” values.
In C#, and many other programming languages, you may see variables more customized in naming conventions as something you would understand in plain English.
For example, “playerSpeed” or or “_fireRate” details (as you may imagine) how fast the Player is moving or the rate to which the Player can fire. You can name these pretty much whatever you want but there are some exceptions and good practices. Variables are commonly added to the top of the script and referenced later in code (usually but not always!).
- In C#, you need to name your variable reference as public or private. this means other outside influences can see/change or NOT see/change your script’s variable value.
NOTE: As a good practice, you should append a prefix of “_” in private variables to easily recognize their reference later in code.
2. Next, add the data type of your variable. These include either: int (integers) — whole numbers, float — decimal values, bool (Booleans) — true or false, or string (text characters or names). In Unity 3D, you may see another data more specifically called a GameObject data type for objects in your scene.
3. You can now name your variable. Make sure you keep this name simple and choose a name that does not include spaces or special characters (like * = + or -) as these will run compile errors.
NOTE: Since we do not use spaces, a good practice is to use what is called “camelCase” lettering. This is where you start with a lowercase on your first word and uppercase on all proceeding words thereafter.
4. Finally, add your optional value proceeded by a semicolon “;”. This is like a period in a line of code. Recall back to your data type as some types may not interpret certain values correctly. For example, a bool is looking for true or false values. If you do not assign a value at all, the variable will default to a its data type default value. For example, int is 0 and float is 0.0 if no value is assigned.
Now you can go back in and replace these variables where its value in your script will benefit from being used to simplify your code!
FINAL TIP: This was mentioned before in a previous post but worth mentioning again: [SerializeField] assignments. These preface private variables and allow for its value to be alterable in Unity’s component Inspector. This can be handy for designers who want to zero-in on the perfect value while still making the variable securely private to other GameObjects and scripts.
This is just scratching the surface of variables. Stay tuned for more examples on how variables are used in code!