Variables are how we store data for use in other places. Now in the preceding example, we want to change the color of an object. Here, we have a piece of code that would do just that:
rend.material.color = new Color(1f, 0.4f, 0.8f);
In this example, we hardcoded a new color; this is considered a bad practice and should be avoided.
To help facilitate this, we use variables; a variable is a name given to space in memory or a storage area. A better way to handle the preceding problem would be to declare a variable and initialize it, or give it a value:
private Color lbColor; lbColor = new Color(0.1f, 0.2f, 0.5f);
Here, the data type is Color and the variable name is lbColor, and we have stored a collection of floats that make a new color.
Now we can assign this newly initialized variable to the color of the material, as follows:
rend.material.color = lbColor;
One benefit of using variables is the ability to use lbColor anywhere a Color data type is needed. Also, we can change lbColor as we did in the preceding example.
Camel casing is important. You may note that when declaring a variable, I used a lowercase m and an uppercase B. This is a highly recommended standard called camel casing, where the first word in a variable declaration is lowercase and all other words are uppercase.
Keep in mind that there are different types of variables, which are determined by their scope. A variable defined in a method will only last for the duration of that method:
[data type] [name];
Class-scope variables will last as long as the class is active, but will have additional protection as a result; they are called access modifiers:
[Access Modifier] [data type] [name];
Some variables are standard data types or what are more commonly referred to as simple data types. Combinations of these data types are used to make the more complex types:
Floating Point: float lbSpeed; Boolean: public bool checkLBToggle = true; Integer: int i = Random.Range(0, 1000);
Some variables are complex data structures:
public Vector3 launchBallHome = new Vector3(0.0f, 0.0f, 4.0f); Renderer rend; private Color lbColor;
You will notice that some of these variable declarations from the LauchBall class start with public or private keywords; these are known as access modifiers.