【发布时间】:2015-08-19 20:27:55
【问题描述】:
我在 Unity 上使用 C# 编程。当我需要在某个时间间隔内重置一个变量时,我倾向于声明很多变量并使用Update() 函数来做我想做的事情。例如,这是我重置技能冷却时间的代码(每当玩家按下射击键时都会调用Shoot()):
using UnityEngine;
using System.Collections;
public class Player : MonoBehavior
{
private bool cooldown = false;
private float shootTimer = 0f;
private const float ShootInterval = 3f;
void Update()
{
if (cooldown && Time.TimeSinceLevelLoad - shootTimer > ShootInterval)
{
cooldown = false;
}
}
void Shoot()
{
if (!cooldown)
{
cooldown = true;
shootTimer = Time.TimeSinceLevelLoad;
//and shoot bullet...
}
}
}
有没有更好的方法来做同样的事情?我认为我当前的代码非常混乱,可读性差。
非常感谢。
【问题讨论】:
-
这个InvokeRepeating 方法。我也喜欢利用StartCoroutine。