会记住值的变量
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 5 课,共 85 课。
Unity 会在每一帧调用 Update(),每次调用都会重新开始:在方法内创建的变量会在方法结束时被丢弃。所以这个计数器永远不会超过 1:
void Update()
{
int frames = 0;
frames++;
}frames++ 会加 1,这是 frames += 1 的简写。但下一帧会再次运行 int frames = 0;,然后重新开始。
要记住从一帧到下一帧的值,请在类内、所有方法外创建变量。这样的变量称为字段:它的生命周期与对象相同,并且该类的每个方法都可以使用它。
int frames = 0;
void Update()
{
frames++;
}现在,frames 会持续计数:1、2、3,以此类推,每一帧加 1。
挑战
简单让植物持续生长。
- 将
int frames = 0;这一行从Update()内移出。 - 将它粘贴到
void Update()上方的类中,这样frames就会成为一个记录计数的字段。
按下 “开始”:植物每一帧都会长高一点。然后按下 “检查”。
亲手试试
using UnityEngine;
public class Grower : MonoBehaviour
{
void Update()
{
int frames = 0;
frames++;
transform.localScale = new Vector3(1, 1 + frames * 0.01f, 1);
}
}
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器