Game Development Reference
In-Depth Information
Now that we've examined how functions work and interact with one another, we will
take a short look at the commands that make variables and functions run: conditional
statements.
Commanding Your Game with Conditional Statements
Once you have defined your data types in variables and told your function when or how it
is to execute, you must put commands into the function to make it actually do things. A
typical command for a computer would look like this:
function Update () {
print(“Hello World!“);
}
This simple function, a variation of the “Hello World!” program that many first-time
programmers learn, directly gives the computer a command: display “Hello World” in
Unity's Console view on every frame. However, games and many other interactive pro-
grams are dependent on ever-changing game states and user interaction. As such, game
programs are often written as conditional statements.
Conditional statements are simple to understand. They say that if something happens,
make something else happen. These are called if statements.
var store : Transform;
var milkInJug : float = 0;
function Update (){
var target : Vector3;
if (milkInJug == 0){
target = store.position;
}
}
In this program—we'll call it AuthorWithDryCereal.js —I defined the variable store
as an object with transform coordinates. Each frame, the program checks if the variable
milkInJug equals 0. If it does, then my target, a variable defined as a Vector3 position, or
set of xyz coordinates, is set to the coordinates of the store transform object.
Another useful type of conditional statements is if-else statements. These not only look
to see if something is happening, but also define what happens if something is not hap-
pening. For example:
var Cake : boolean = false;
function Update () {
if (Cake == true) {
print(“Yum, cake!“);
} else {
print(“The cake is a lie“);
}
}
Search WWH ::




Custom Search