首页 > 解决方案 > 如何使 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); 
         }
     }
}

标签: c#unity3d

解决方案


您对问题的根源是正确的:您正在检查每一帧是否按下了键。释放“e”键后的框架,笔记本电脑 UI 将关闭。

你有两个明确的选择来解决这个问题。

  1. 添加一个切换。
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
                }
            }
        }
  1. 跟踪窗口打开的时间。

首先,在函数范围之外添加一个变量来保存所需的关闭时间。

    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);
                    }
                }
            }
        }

推荐阅读