Game Development Reference
In-Depth Information
Declaring a variable is a four-part process:
1. Type var to tell the program that you are declaring a variable.
2. Name the variable—for this example, use myNumber . You can name a variable almost
anything you want as long as its name begins with a letter, the $ symbol, or the
underscore character. However, I recommend that you give variables descriptive
names based on their function and the information they are storing.
3. Use a colon to declare what type of data is being stored in the variable. In this case
you're storing an integer (a whole number without a decimal point) in myNumber .
4. Declare the value of the variable and finish the line with a semicolon—the punctua-
tion that finishes all statements in scripts.
Uses of Variables
By storing information in a variable, you can access it in your code as many times as you
like by referencing the variable name. If you want to change that information at any time,
you only need to change the value of the variable rather than changing each instance of
that information in your program.
Variables are one of the most useful elements in Unity scripting, because they are uti-
lized to assign information such as a character's run speed, a gun's fire rate, the range for
an object's actions, or even the sound or animations of game mechanics. When a vari-
able has been declared with var , it also becomes accessible through the Unity interface
in the Inspector view. Figure 10.6 shows variable settings on a
handgun script. The values controlled by the variables allow this
script to become the code for many other types of guns.
By attaching a script to a game object as a component, you
can change variable settings in the Inspector view without
having to dive back into your code. Any variable values in the
Inspector view override the values in the code itself.
Figure 10.6
The variables for
the Handgun.js
script offer lots of
versatility
Types of Data Stored in Variables
Variables can hold many types of information, but it is important to understand what
those types are and how to tell the computer you are using them. Unity variables can
contain hundreds of types of data. Here are some of the most common that you will see
as you script. Many of these will also be utilized in scripts later in the chapter, so now is a
good time to familiarize yourself with them.
Float Values Float values, like integers, store number information. However, float vari-
ables can store numbers with decimal points:
var myFloat : float = 3.5;
Search WWH ::




Custom Search