教程地址(观看视频需翻墙):
https://unity3d.com/cn/learn/tutorials/topics/scripting/if-statements?playlist=17117
教程代码实例:
using UnityEngine;
using System.Collections;
publicclass 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 isgreater than the hottest drinking temperature...
if(coffeeTemperature > hotLimitTemperature)
{
// ... do this.
print("Coffee is too hot.");
}
// If it isn't, but the coffeetemperature is less than the coldest drinking temperature...
elseif(coffeeTemperature <coldLimitTemperature)
{
// ... do this.
print("Coffee is too cold.");
}
// If it is neither of those then...
else
{
// ... do this.
print("Coffee is just right.");
}
}
}
这个实例的功能是测试咖啡是否到了适合喝的温度,刚开始的时候按空格咖啡还很烫,过一会儿按空格显示可以喝了,当咖啡温度低于规定的值时,按空格显示太冷不能喝了。
if/else的逻辑顺序很简单,里面有一个我曾写过的计时功能,自减计时,学习。
coffeeTemperature -=Time.deltaTime *5f;
这个使用范围很广,后面还会用到很多次。