我如何设置一个带键的布尔值并使其像一个开关

how do i set a bool with key and make it like a switch

我想制作一个脚本,通过一个键(在我的例子中是“e”)打开照片模式并将其保持在打开状态,直到我再次按下键(e)但我不能,因为它不断更新它代码:

If (Input.GetKey("e"))
      {
         Debug.Log("e");
         if (isphoto == true)
         {

             Debug.Log("true");
             MaxtimetoSwitch = 1;
             while (MaxtimetoSwitch >= 1)
             {
                 isphoto = false;
                 MaxtimetoSwitch = MaxtimetoSwitch - 1;


             }
         }
         else
         {
             Debug.Log("false");
             MaxtimetoSwitch = 1;
             while (MaxtimetoSwitch >= 1)
             {
                 isphoto = true;
                 MaxtimetoSwitch = MaxtimetoSwitch - 1;

             }
         }
         
             Debug.Log("false");
             MaxtimetoSwitch = 1;
             while (MaxtimetoSwitch >= 1)
             {
                 isphoto = true;
                 MaxtimetoSwitch = MaxtimetoSwitch - 1;

        }

使用 Input.GetKeyDown 怎么样?

它 returns true 仅在 一帧 键按下时。您不必关心每一帧的输入,因为您只对单击事件感兴趣。

private void Update()
{
    if(Input.GetKeyDown(KeyCode.E))
    { 
        // invert bool flag
        isphoto = !isphoto; 
        
        // TODO: Open or close photo window according to isPhoto
        // e.g.
        photoWindow.SetActive(isphoto);
    }
}
 

或者如果您的目标是等待直到按键被按下一定时间,然后执行例如

// Adjust in the Inspector
[SerializeField] private float switchThreshold = 1f;

private float timePressed;

private void Update()
{
    if(Input.GetKeyDown(KeyCode.E))
    { 
        // first frame -> reset counter
        timePressed = 0f;
    }
    else if(Input.GetKey(KeyCode.E) && timePressed < switchThreshold)
    {
        // increase counter by the time passed since last frame
        timePressed += Time.deltaTime;
    
        // once counter exceeds
        if(timePressed >= switchThreshold)
        {
            isphoto = !isphoto; 
            
            // TODO: Open or close photo window according to isPhoto
            // e.g.
            photoWindow.SetActive(isphoto);
        }
    }
}