【问题标题】:Is there a better way to reset cooldown on Unity?有没有更好的方法来重置 Unity 的冷却时间?
【发布时间】: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...
        }
    }
}

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

非常感谢。

【问题讨论】:

标签: c# unity3d


【解决方案1】:

使用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;
    }
}

【讨论】:

    【解决方案2】:

    没有Invoke的方式更容易控制:

    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;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多