IF Statements
Checked with version: 4
-
Difficulty: Beginner
How to use IF statements to set conditions in your code.


IF Statements
Beginner Scripting
IfStatements
Code snippet
using UnityEngine;
using System.Collections;
public class IfStatements : MonoBehaviour
{
float coffeeTemperature = 85.0f;
float hotLimitTemperature = 70.0f;
float coldLimitTemperature = 40.0f;
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
TemperatureTest();
coffeeTemperature -= Time.deltaTime * 5f;
}
void TemperatureTest ()
{
// If the coffee's temperature is greater than the hottest drinking temperature...
if(coffeeTemperature > hotLimitTemperature)
{
// ... do this.
print("Coffee is too hot.");
}
// If it isn't, but the coffee temperature is less than the coldest drinking temperature...
else if(coffeeTemperature < coldLimitTemperature)
{
// ... do this.
print("Coffee is too cold.");
}
// If it is neither of those then...
else
{
// ... do this.
print("Coffee is just right.");
}
}
}
#pragma strict
private var coffeeTemperature:float = 85.0f;
private var hotLimitTemperature:float = 70.0f;
private var coldLimitTemperature:float = 40.0f;
function Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
TemperatureTest();
coffeeTemperature -= Time.deltaTime * 5f;
}
function TemperatureTest ()
{
// If the coffee's temperature is greater than the hottest drinking temperature...
if(coffeeTemperature > hotLimitTemperature)
{
// ... do this.
print("Coffee is too hot.");
}
// If it isn't, but the coffee temperature is less than the coldest drinking temperature...
else if(coffeeTemperature < coldLimitTemperature)
{
// ... do this.
print("Coffee is too cold.");
}
// If it is neither of those then...
else
{
// ... do this.
print("Coffee is just right.");
}
}
import UnityEngine
import System.Collections
public class IfStatements(MonoBehaviour):
private coffeeTemperature as single = 85.0F
private hotLimitTemperature as single = 70.0F
private coldLimitTemperature as single = 40.0F
private def Update():
if Input.GetKeyDown(KeyCode.Space):
TemperatureTest()
coffeeTemperature -= (Time.deltaTime * 5.0F)
private def TemperatureTest():
// If the coffee's temperature is greater than the hottest drinking temperature...
if coffeeTemperature > hotLimitTemperature:
// ... do this.
print('Coffee is too hot.')
elif coffeeTemperature < coldLimitTemperature:
// If it isn't, but the coffee temperature is less than the coldest drinking temperature...
// ... do this.
print('Coffee is too cold.')
else:
// If it is neither of those then...
// ... do this.
print('Coffee is just right.')