Ramen with Eggs
Ramen with Eggs

Reputation: 85

Is there a better way to reset cooldown on Unity?

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.

Upvotes: 1

Views: 2623

Answers (2)

Krzysztof Bociurko
Krzysztof Bociurko

Reputation: 4662

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

}

Upvotes: 1

Anas iqbal
Anas iqbal

Reputation: 1044

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

Upvotes: 1

Related Questions