If and Else
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 6 of 85.
A bool holds one of two values: true or false. Is the door open? Is the player on the ground? Is the game over?
bool gameOver = false;An if runs its lines only when its condition is true, and an else runs its lines when it is not. The braces { } hold the lines that belong to each part:
if (gameOver)
{
transform.position = new Vector3(0, -2, 0);
}
else
{
transform.position = new Vector3(0, 2, 0);
}This sinks an object out of sight when the game is over and keeps it up while the game goes on. Code like this goes inside a method, such as Update(), never after the class's last }.
Unity answers questions with bools too. Input.GetKey(KeyCode.Space) is true while the player holds the space bar and false the rest of the time, so Update() can ask it every frame.
Challenge
EasyHolding Space should lift the gate.
- Below the two comments in
Update(), writeif (open)withtransform.position = new Vector3(0, 3, 0);in its braces. - After it, write
elsewithtransform.position = new Vector3(0, 1, 0);in its braces.
Press Play, click the game and hold Space: the gate rises, and drops when you let go. Then Check.
Try it yourself
using UnityEngine;
public class Gate : MonoBehaviour
{
void Update()
{
bool open = Input.GetKey(KeyCode.Space);
// If open is true, move the gate to (0, 3, 0).
// Otherwise, move it to (0, 1, 0).
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground