Game Development Reference
This program will print out “Y is greater than or equal to X” because the
conditional statement inside the parentheses of the if statement will
equate to false. If X were given a value of 20, the program would print
out “X is greater than Y”.
Unity Hands On
Step 1. Download Chapter One/ifelse.zip from the Web site, unzip, and
open in Unity. In the Project, double-click on falling to open the scene.
In the Scene you will see a small white sphere. Attached to the sphere
is the script called fallandgrow.js .
Step 2. Play the application. The sphere will appear to fall as its y
position is changed constantly by the script.
Step 3. Open the fallandGrow.js script and make the changes shown
in Listing 1.16 .
Listing 1.16 Making a Game Object Fall to a Certain Position
and Then Stop
var speed: float = 0.1;
var groundLevel: int = -4;
function Update ()
if(transform.position.y > groundLevel)
//keep moving down
transform.position.y = transform.position.y - speed;
Step 4. Save and play. Watch as the sphere moves down the
screen until it stops. What is occurring is that the y position is
constantly being reduced by 0.1. While the value of the y position
remains larger − 4, the code inside the if statement will continue
to be processed. As point y becomes greater than or equal to the
groundLevel , that line of code is skipped and thus the sphere no
longer has its y position modified.
Step 5. We are now going to modify the code to make the sphere
start to grow when it stops moving. We know it will stop moving
when the conditional statement in Listing 1.16 becomes false;
therefore, by adding some growth code into an else we can have
it execute, but only when the sphere stops moving. Update the
fallandGrow.js script to reflect Listing 1.17 .