有没有更好的方法可以在Unity上重置冷却时间? [英] Is there a better way to reset cooldown on Unity?

查看:71
本文介绍了有没有更好的方法可以在Unity上重置冷却时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Unity上用C#编程.每当我需要在某个时间间隔内重置变量时,我都会倾向于声明很多变量,并使用 Update()函数执行所需的操作.例如,这是我的代码,用于重置技能的冷却时间(每当玩家按下射击键时,都会调用 Shoot()):

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.

非常感谢.

推荐答案

使用 Invoke 可以节省很多变量.

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

这篇关于有没有更好的方法可以在Unity上重置冷却时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆