Home > Back-end >  Input.GetKey("f") does not do anything when f i pressed
Input.GetKey("f") does not do anything when f i pressed

Time:08-15

Within my, if function, the Input.GetKey("t") command does not work. The Restart method is called when I remove the contents from the if function and place them outside.

using UnityEngine; using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour {
    bool gameHasEnded = false; 

    public float restartDelay = 2f;
    public GameObject LevelFailedUI;
    public GameObject LevelCompleteUI;

    public void CompleteLevel (){

        if (LevelFailedUI == true){
        LevelCompleteUI.SetActive(true);
        }
    }
    public void EndGame () {
        
        if (gameHasEnded == false)
        {
            gameHasEnded = true;
            LevelFailedUI.SetActive(true);
            if (Input.GetKey("t"))       //nothing happens when "t" is pressed.
            { 
                Invoke("Restart", restartDelay);
            }
        }

    }

    void Restart () 
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        LevelFailedUI.SetActive(false);
    } }

CodePudding user response:

It won't work because unity has to be inside the function and also hasn't reached the check before reaching the if statement and you press the button during one frame which is basically impossible. You have to check for input constantly that is why it is done inside the Update function.

void Update() {
  if (Input.GetKey(KeyCode.T) && gameHasEnded) {
    Invoke("Restart", restartDelay);
  }
}
public void EndGame() {
  if (gameHasEnded == false) {
    gameHasEnded = true;
    LevelFailedUI.SetActive(true);
  }
}
  • Related