2D Galaxy Shooter — Explaining Variables
Hello all!
Today, I will be talking about variables! Variables are used as building blocks for programming.
An example of this would be health. Games don’t know that we die if we get hit three times without a variable setting our health.
Most of the time, you will add your variables right under the “MonoBehavior”.
There are three things a variable need with an optional fourth:
a public or private reference, data type, a name, and an optional value.
References
References can either be public or private depending on what you need it for. Let’s use the speed of my player for example, not everyone needs to see the speed of my player, so I would set this to private. Now say that you are adding a health variable in a shooter, you would want them public so your enemies can have access to the script and hurt you.
With private references, it is a best practice to always add an underscore before the name of your variable, like “private float _speed = 3.5f;”
Also, you can always change private references where it can be seen in the inspector anyways using a [SerializeField] behind the variable
Data Types
There are four very useful data types in variables:
- Bool — True or false
public bool blueSky = true; - Float — Decimal value
public float pi = 3.14159265359f;
Note: “f” is required after any decimal value - Int — Whole value
public int year = 2021; - String — Names
public string myName = “Marcus Cohee”;
Names
Names are used to reference the variable in the code.
We use Camel Casing for our names here. For example: “myName” would look like “My Name” in the inspector when looking at the script tab.
Optional Value
The last part of the variable is to give it a value. To start out with, they are given the value of 0, false, or nothing. That 0 can get messy if used with multiplication, so it’s usually a good idea to add a value.
That’s how variables work!
Thank you for your time!