GUI.Label not working.

I’m trying to make a keyboard listener, so I can display it on screen for the player (If you press A, then your action button will be set to A and a square will pop on screen so you can confirm). Like in this image alt text. But it’s not working out.

Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ShowOnScreen : MonoBehaviour {
	
	 void OnGUI()
	{
		string keyCode;
		Event e = Event.current;
		keyCode = e.ToString();
		if (e.isKey)
		{
		GUI.Label(new Rect(Screen.width / 2, Screen.height / 2, 200f, 200f), keyCode);
			//Debug.Log("Detected key code: " + keyCode);
		}
	}
}

Also, is there a better way to create a keyboard listener?

The problem you are facing is that the label is displayed for 1 single frame when you call GUI.Label(). You would usually call GUI.Label() in every call to OnGUI(), and simply change the string.

Here is some example code, but mind you I’m not very familiar with events. That handling of the event should probably be given some more care:

public class ShowOnScreen : MonoBehaviour {

    string latestEvent;

	void OnGUI()
	{
		Event e = Event.current;
		string currentEvent = e.ToString();
		if(latestEvent!= currentEvent){
			latestEvent = currentEvent; // Change label output when new event was discovered
		}

		// Make sure this is called every frame to keep it visible
		GUI.Label(new Rect(Screen.width / 2, Screen.height / 2, 200f, 200f), latestEvent);
	}
}

Edit: I just saw you asking for another keyboard listener. Simple, just use Input.GetKeyDown() in your Update():

void Update(){
    // GetKeyDown is true the first frame the key is down
    bool pressedW = Input.GetKeyDown(KeyCode.W); 
    bool pressedSpace = Input.GetKeyDown(KeyCode.Space);

    // GetKey is true every frame the key is down
    bool isShiftDown = Input.GetKey(KeyCode.LeftShift);

    if(pressedW){/*do something*/}
    if(pressedSpace){ /*do something*/}
}

I worked arround like this, thank you guys for the help :slight_smile:

public class ShowOnScreen : MonoBehaviour
{
    public Text playerInput;

    void Start()
    {
        Canvas.ForceUpdateCanvases();
    }


    void OnGUI()
    {

        if (Input.anyKeyDown)
        {
            playerInput.text = Input.inputString;
            Debug.Log(Input.inputString);
        }
    }