Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...