Is there a better way to reset cooldown on Unity?

泄露秘密 提交于 2021-01-28 08:14:47

问题


I'm programming in C# on Unity. When ever I need to reset a variable in a certain interval, I would tend to declare a lot of variables and use the Update() function to do what I want. For example, here is my code for resetting a skill's cooldown (Shoot() is called whenever player presses shoot key):

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

Is there any better ways to do the same thing? I think my current code is extremely messy with bad readability.

Thanks a lot.


回答1:


Use Invoke this will save you a lot of variables.

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:


A way without Invoke that is a bit easier to control:

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

}


来源:https://stackoverflow.com/questions/32070533/is-there-a-better-way-to-reset-cooldown-on-unity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!