What are variables?
You can think of variables as containers for various types of data. Data can be stored and altered to create game systems such as a scoring system, item names, movement speed, and deciding whether the player has died.
Three components go into creating a variable with the optional fourth.
1. Access modifiers:
Access modifiers decide if any other classes or methods can access the variable. The two most common access modifiers are public and private.
Public: Any class and method can call a variable with the public tag. Public variables can even be seen and changed in the Unity inspector.
Private: Only the class and method the variable can call it. Private variables can’t be seen or changed in the Unity inspector.
Private variables can’t naturally be seen and changed in the Unity inspector. However, [serializefield] can be used to override not using the variable in the inspector while still preventing the variable from being accessed by other classes and methods.
2. Data types:
Data types decide the type and size of the data stored in the variable. Some common data types include:
int: Used to store integers. Examples: 0, 1 ,-1, 12, 200, -200
string: Used to store a series of Characters and numbers. Must use double quotation marks to indicate what is part of the string. Examples: “This is a string.”, “120$ is also a string.”
float: This is used to store numbers with decimal points. The numbers must have the letter “f” put after them to indicate it is a floating-point number. Examples: 5.0f, 5.5f, 0.1f
bool: Used to return either “true” or “false”
This is what it sounds like, just the name of the variable. It is common practice to use camel casing for variable Names. Camel casing starts the first word lower case and every word after that upper case. Examples: playerMoveSpeed, eBay, item, camelCasing. It is worth noting that the names have to be one continuous name. Private variable names typically start with an underscore: examples: _item, _camelCasing.
4. Assigned values (Optional):
You don’t have to assign a variable a set value directly. Instead, you could have the value set somewhere else, like in the Unity inspector.