定时生成
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 63 课,共 85 课。
每隔几秒生成一次内容的生成器需要一个计时器。Time.deltaTime表示上一帧耗费的时间,因此在每次Update()中把它累加到一个字段里,就能得到已经过去的秒数。当总时间达到间隔时,就生成内容,并从总时间中减去这个间隔。
这个喷泉每半秒喷出一滴水:
public GameObject dropPrefab;
public float interval = 0.5f;
float timer;
void Update()
{
timer += Time.deltaTime;
if (timer >= interval)
{
Instantiate(dropPrefab, transform.position, Quaternion.identity);
timer -= interval;
}
}timer -= interval会保留剩余时间:如果这一帧结束时经过了 0.51 秒,下一个半秒就会从 0.01 秒开始计时,这样水滴就能保持节奏。timer = 0会丢掉这段剩余时间,因此每滴水都会稍微晚一些喷出,而且在长时间运行的游戏中,延迟会不断累积。timer是私有的,因为没人需要在 Inspector 中设置它。
挑战
中等每隔 interval 秒掉落一个箱子(在 Inspector 中设置为 2)。
- 添加
float timer;和int count;字段。在Update()中,将Time.deltaTime加到timer上。 - 当
timer >= interval时,调用Instantiate(boxPrefab, transform.position, Quaternion.identity);,并从timer中减去interval。 - 然后将
count加 1,并记录"Box " + count。
按下 Play:每隔 2 秒掉落一个箱子,Console 中会依次显示 Box 1、Box 2。然后点击 Check。
亲手试试
using UnityEngine;
public class BoxDropper : MonoBehaviour
{
public GameObject boxPrefab;
public float interval = 1f;
void Update()
{
// 每隔 interval 秒:生成一个盒子,并记录 "Box 1"、"Box 2"……
}
}
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器