有没有更好的方法来重置 Unity 的冷却时间? [英] Is there a better way to reset cooldown on Unity?
本文介绍了有没有更好的方法来重置 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屋!
查看全文