gpt4 book ai didi

c# - 在几秒钟之间限制按钮按下?

转载 作者:行者123 更新时间:2023-12-05 04:08:07 28 4
gpt4 key购买 nike

如何使按钮按下功能仅在 # 秒之间起作用?例如,允许用户随时按 E,但每 5 秒执行一次动画?我试过 Invoke 但它似乎没有正常工作。我还尝试了时间戳和 StartCoroutine (waitforseconds)。

这是我得到的,所以你可以看到:

    void Update()
{
if (triggerIsOn && Input.GetKeyDown(KeyCode.E))
{
drinkAmin.Play("DrinkVodka");
StartCoroutine(letsWait());

}
}

IEnumerator letsWait(){

Debug.Log ("lets wait works!");
yield return new WaitForSeconds (5);
TakeAshot ();
}

一切正常,但不是间隔 5 秒,而是在每次按下按钮后每 5 秒工作一次。所以,这不能正常工作。谁能帮我?这里有点迷路。谢谢!

最佳答案

我想出了一个解决方案,通过使用协程和每个协程调用的唯一标识符来消除 Unity 中的输入事件。

public class Behaviour : MonoBehaviour
{
private Guid Latest;

void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
// start the debounced input handler coroutine here
StartCoroutine(Debounced());
}
}

private IEnumerator Debounced()
{
// generate a new id and set it as the latest one
var guid = Guid.NewGuid();
Latest = guide;

// set the denounce duration here
yield return new WaitForSeconds(3);

// check if this call is still the latest one
if (Latest == guid)
{
// place your debounced input handler code here
}
}
}

这段代码的作用是为每次调用 Debounced 方法生成一个唯一的 id,并设置最新的 Debounced 调用的 id。如果最新的调用 ID 与当前调用 ID 匹配,则执行代码。否则,在此之前发生了另一个调用,因此我们不运行该代码。

Guid 类位于 System 命名空间中,因此您需要在文件顶部添加一条 using 语句:using System;.

关于c# - 在几秒钟之间限制按钮按下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47985737/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com