我主要把这个问题发在这里,是因为我觉得那些真正懂行的人可能会觉得这很有趣。不过,如果你发现可以改进的地方并愿意提出建议,请尽管分享。让我知道我还漏掉了什么。
之前我一直在想办法让玩家可以释放狗,但只能每隔一定时间释放一次。我在这个问题上纠结了很久,始终找不到解决办法,最后只好放弃了。
或者至少我尝试过放弃。我试着在谷歌上搜索答案,看看能不能理解别人在说什么——只要能看懂他们的解释,我就心满意足了,然后直接复制他们的代码。
但我完全看不懂那些解答。于是继续搜索。最后我意识到(或者说是被提醒?)一个事实:如果你直接在类中声明一个变量,那么当任何方法改变这个变量的值时,其他方法也能看到这个变化。经过好一阵琢磨,我结合这一点和最近别人教我的关于Invoke和创建自定义方法的知识,终于弄出了这段代码。
这代码确实很不优雅,但至少能跑,所以——
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControllerX : MonoBehaviour
{
public GameObject dogPrefab;
public InputAction fireAction;
private float checkIfCoolDown = 0;
public float estimatedCoolDownTime = 1;
// Start is called before the first frame update
void Start()
{
fireAction.Enable();
}
// Update is called once per frame
void Update()
{
// On spacebar press, and cooldown 0, send dog
if (fireAction.triggered && checkIfCoolDown == 0)
{
NoSpamDogs();
}
}
void NoSpamDogs()
{
//Fires dog and then activates TimerStart after a delay so it doesn't instantly become 0 and interfere with fire
Instantiate(dogPrefab, transform.position, dogPrefab.transform.rotation);
Invoke("TimerStart", 0.000000001f);
}
void TimerStart()
{
//Turns check to one, disabling fire, and after cool down time does CooldownEnd
checkIfCoolDown = 1;
Invoke("CooldownEnd", estimatedCoolDownTime);
}
void CooldownEnd()
{
//Turns check back to 0, ending cooldown and enabling fire
checkIfCoolDown = 0;
}
}
评论 (0)