kamiljan
kamiljan

Reputation: 1

How to perform an action after key pressed?

I tried to hide a text in Unity after caps was pressed, but it doesn't work, it stops before "while". I'm quite a not up to par programmer, so anyone more experienced?

private float TurnOffInfoText()
    {
       
      
        bool IsCapsPressed =   Input.GetKeyDown(KeyCode.CapsLock);
       
        while (IsCapsPressed == true)
        {
            
            EndOfGameText.enabled = false;
        }
      
        return 0;
        
}

Upvotes: 0

Views: 189

Answers (1)

derHugo
derHugo

Reputation: 90659

Why does this even return a value?

Also your while loop would completely freeze the entire App and even the Unity Editor application! Within the loop the IsCapsPressed value is never ever changed!

I don't see where your method is called from but if you never experienced a freeze so far then "luckily" the key never went down in the same frame so far.

Usually you would rather poll the input every frame. By a simple look into the API for Input.GetKeyDown:

private void Update ()
{
    if(Input.GetKeyDown(KeyCode.CapsLock))
    {  
        EndOfGameText.enabled = false;
    }      
}

Upvotes: 6

Related Questions