02 / 11 · 5 分钟
基础
方法与游戏循环
到目前为止的项目
还没有项目。你在学 Unity 会替你调用的三个方法——从第 06 课起你就会看到它们运行。
方法就是一段起了名字、随时可以让它跑起来的代码。Unity 会自动帮你调用其中三个。
动态图解
Awake 和 Start 在对象刚被创建时各跑一次。Update 则一遍又一遍,大约每秒 60 次。
每天都要写的三个方法
Lifecycle.cs
void Awake() { /* set up my own references */ }
void Start() { /* everything else exists now */ }
void Update() { /* runs every frame */ }void 表示这个方法不返回任何东西。( ) 里放的是入参 —— 这里空着。
每个对象都会先跑 Awake 再跑 Start,所以在 Start 里可以放心用其他对象。
Update 就是你的游戏循环:读输入、移动、计时、做条件检查。
Time.deltaTime —— Update 唯一的规则
配置好的 PC 每秒调用 Update 的次数比低端手机多。乘上 Time.deltaTime(距上一帧过去了多少秒)之后,在任何设备上移动速度都一样。
动态图解
每个方框就是一次 Update() 调用。上面那半部分每次调用加 5 HP,所以高性能设备一秒结束时跑到了 50 HP;下面那半部分加的是 5 HP × deltaTime,两排最后都停在同样的 5 HP。
✖ 3 units per frame
frame-dependent
transform.position += Vector3.forward * 3f;✓ 3 units per second
frame-independent
transform.position += Vector3.forward * 3f * Time.deltaTime;自己写一个方法
Damage.cs
int hp = 100;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
TakeDamage(20); // call it
}
void TakeDamage(int amount) // amount = the input
{
hp -= amount;
Debug.Log("HP left: " + hp); // prints to the Console
}