Day 7: Variables! — The building blocks of programming

Tyler Smallwood
3 min readApr 29, 2021

--

Variables, article1000.com

Variables are one of the most important aspects of coding. Everything we do has data, but how do we hold that data and read the data. Variables allow us to read the data, compare the data, and more. Best way to think of a variable is that its a container for data.

There are a few of important things to think of when it comes to variables. First will be the access modifier. Next will be the variable type. And lastly, which this can be optional, is assigning data to the variable.

Access modifiers are what determine who can read or rewrite the data from the scripts. When you give a variable a public access modifier, any other script or game object will be able to access it and change the data. Even in the inspector, you will be able to adjust the data.

public laser cool down.

Here I have laserCoolDown public because later I plan to add a powerUP that will lower the cool down so you can fire faster.

If the variable is set as private, only the script that has the variable will be able to read or change the data. When it is private, in the inspector, you wont be able to see or adjust the data. If you would like to be able to change the data on a private variable use [SerializeField]. This is a benefit of MonoBehaviour. Setting the private variable to SerializeField, it will show up in the inspector.

Private speed but allow to change in the inspector.

There are a few best practices when it comes to naming conventions. One is to use camelCase. For variables first letter will be lower case and the second word will be capital. For public variables don’t add an underscore and for private add an underscore. This will allow you or anyone to know if a variable is public or private if they are very far down in the script.

Variable types

There are a few variables. The main ones you might use in Unity will be float, int, bool, and string.

Float is used for numbers that may need decimal numbers such as 5.2. If using float in unity you will need to add an f at the end of the number, so there fore 5.2f.

Int is for whole numbers, such as -2 , -1, 0, 1, 2.

Bool is just for true or false. Used to check to see if something is done or not. Such as canFire.

String is a string of characters that are put together.

When it comes to creating global variables, it is not required to give the variables data at the beginning. You can always give the variables data later on in the script.

Variables are very useful when it comes to programming. Using them for everything from making sure the player has a key to open a door to seeing if the player has a new high score to add on the the high score board.

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet