C# 限位按钮是否在秒之间按下?
如何使按键功能仅在#秒之间工作?例如,允许用户随时按E键,但每5秒执行一次动画?我试过调用,但它似乎没有发挥应有的作用。我还尝试了timestamp和startcroutine(waitforseconds) 以下是我得到的,你可以看到:C# 限位按钮是否在秒之间按下?,c#,unity3d,C#,Unity3d,如何使按键功能仅在#秒之间工作?例如,允许用户随时按E键,但每5秒执行一次动画?我试过调用,但它似乎没有发挥应有的作用。我还尝试了timestamp和startcroutine(waitforseconds) 以下是我得到的,你可以看到: void Update() { if (triggerIsOn && Input.GetKeyDown(KeyCode.E)) { drinkAmin.Play("DrinkVodka");
void Update()
{
if (triggerIsOn && Input.GetKeyDown(KeyCode.E))
{
drinkAmin.Play("DrinkVodka");
StartCoroutine(letsWait());
}
}
及
这一切都可以工作,但不是5秒之间,而是在每次按下按钮后每5秒工作一次。所以,这并没有起到应有的作用。有人能帮我吗?这里有点迷路了。
谢谢 你说的是所谓的“脱口而出者”。关于这一点,已经有一个很好的SO问题:-尝试使用其中一种方法。我提出了一个解决方案,通过使用协程和每个协程调用的唯一标识符来消除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代码>在动画开始时分离事件并在5秒后重新连接会更容易吗?这可能会起作用,但似乎不是明智之举@KMC
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
}
}
}