Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 有没有更好的方法重置Unity的冷却时间?_C#_Unity3d - Fatal编程技术网

C# 有没有更好的方法重置Unity的冷却时间?

C# 有没有更好的方法重置Unity的冷却时间?,c#,unity3d,C#,Unity3d,我在用C#on Unity编程。每当我需要在某个时间间隔内重置一个变量时,我都倾向于声明许多变量,并使用Update()函数来执行我想要的操作。例如,下面是我重置技能冷却时间的代码(shot()在玩家按下shot键时被调用): 有没有更好的方法来做同样的事情?我认为我当前的代码非常混乱,可读性很差 非常感谢。使用Invoke这将为您节省大量变量 public class Player : MonoBehavior { private bool cooldown = false;

我在用C#on Unity编程。每当我需要在某个时间间隔内重置一个变量时,我都倾向于声明许多变量,并使用
Update()
函数来执行我想要的操作。例如,下面是我重置技能冷却时间的代码(
shot()
在玩家按下shot键时被调用):

有没有更好的方法来做同样的事情?我认为我当前的代码非常混乱,可读性很差


非常感谢。

使用
Invoke
这将为您节省大量变量

public class Player : MonoBehavior
{
    private bool cooldown = false;
    private const float ShootInterval = 3f;

    void Shoot()
    {
        if (!cooldown)
        {
            cooldown = true;

            //and shoot bullet...
            Invoke("CoolDown", ShootInterval);
        }
    }

    void CoolDown()
    {
        cooldown = false;
    }
}

一种没有调用
的方法,更易于控制:

public class Player : MonoBehavior
{

    private float cooldown = 0;
    private const float ShootInterval = 3f;

    void Shoot()
    {
        if(cooldown > 0)
            return;

        // shoot bullet
        cooldown = ShootInterval;
    }

    void Update() 
    {
        cooldown -= Time.deltaTime;
    }

}
这个方法。我也喜欢利用这个机会。
public class Player : MonoBehavior
{

    private float cooldown = 0;
    private const float ShootInterval = 3f;

    void Shoot()
    {
        if(cooldown > 0)
            return;

        // shoot bullet
        cooldown = ShootInterval;
    }

    void Update() 
    {
        cooldown -= Time.deltaTime;
    }

}