c# - 如何使 InputGetKeyDown 持续超过一帧?
问题描述
因此,如果我按“E”键,此脚本会召唤一个 UI。问题是当我按下它时,它立即消失,因为它应该是一个单帧。如何让它持续更长的时间,比如 5 秒?
if (Physics.Raycast(transform.position, fwd, out hit, rayLength, layerMaskInteract.value))
{
if(hit.collider.CompareTag("Object"))
{
raycastedObj = hit.collider.gameObject;
if(Input.GetKeyDown("e"))
{
Debug.Log("done");
LaptopUI.SetActive(true);
}
else
{
LaptopUI.SetActive(false);
}
}
}
解决方案
您对问题的根源是正确的:您正在检查每一帧是否按下了键。释放“e”键后的框架,笔记本电脑 UI 将关闭。
你有两个明确的选择来解决这个问题。
- 添加一个切换。
if (Physics.Raycast(transform.position, fwd, out hit, rayLength, layerMaskInteract.value))
{
if(hit.collider.CompareTag("Object"))
{
raycastedObj = hit.collider.gameObject;
if(Input.GetKeyDown("e"))
{
Debug.Log("toggled");
LaptopUI.SetActive(!LaptopUI.activeSelf);//Invert the value
}
}
}
- 跟踪窗口打开的时间。
首先,在函数范围之外添加一个变量来保存所需的关闭时间。
private float CloseAtTime;
然后在我们打开笔记本电脑用户界面时设置我们的关闭时间。
if (Physics.Raycast(transform.position, fwd, out hit, rayLength, layerMaskInteract.value))
{
if(hit.collider.CompareTag("Object"))
{
raycastedObj = hit.collider.gameObject;
if(Input.GetKeyDown("e"))
{
Debug.Log("opened");
CloseAtTime = Time.time + 5f;//Close around 5 seconds from now.
LaptopUI.SetActive(true);
}
else
{
if(LaptopUI.activeSelf && Time.time >= CloseAtTime)
{
Debug.Log("closed");
LaptopUI.SetActive(false);
}
}
}
}
推荐阅读
- android - 随着时间的推移,Android 会减慢 TranslateAnimation
- javascript - css flex 和输入框的问题
- c++ - 使用 std::transform() 添加四个向量 c++
- c# - 无法将反序列化的 json 放入 gridview
- java - Android studio - 如何使用长按按钮
- java - 尽管没有错误,但我的应用程序无法在 android studio 中运行,我想怎么办?
- postgresql - Django 数据库从 SQLlite 更改为 PostgreSQL 日期时间字段错误全局解决所有模型字段
- python - CR.CR_SERVER_LOST, "查询期间丢失与 MySQL 服务器的连接")
- amazon-web-services - 使用 react-native 和 amazon pinpoint 以编程方式发送推送通知?
- r - 使用自定义字典模糊匹配和替换数据框中的字符串