TextArea does not fire KeyDown events

The TextArea control (along with the TextField control) does not fire an EventType.KeyDown event when a keyboard key is pressed. Why is this, and what is a good workaround?

Here is a script that demonstrates this:

private string textAreaString = "Type here:                  !";

void Update () {
	// Only happens on mouse click
	if(Input.anyKeyDown)
		Debug.Log("SUCCESS! Input.anyKeyDown is true!");	
	// Only happens on mouse click
	if(Input.anyKey)
		Debug.Log("SUCCESS! Input.anyKey is true!");
}

void OnGUI ()
{
	textAreaString = GUILayout.TextArea(textAreaString);
	// Only happens on mouse click
	if(Event.current.type == EventType.KeyDown)
		Debug.Log("SUCCESS! EventType.KeyDown fired!");
	// Only KeyUp and used events happen
	if(Event.current.type != EventType.Repaint && Event.current.type != EventType.Layout )
		Debug.Log("Current event " + Event.current.type + " at " + Time.timeSinceLevelLoad);
}

I’m currently running Unity 4.0.1f2 on PC.

Hi, It happens when the event gets used by any other control. In this case, the KeyDown event is getting used by the TextArea control and so it doesnt fire.

–

1 Answer

1

This could be a workaround

 private string textAreaString = "Type here:                  !";
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
        // Only happens on mouse click
        //if (Input.anyKeyDown)
        //    Debug.Log("SUCCESS! Input.anyKeyDown is true!");
        // Only happens on mouse click
        //if (Input.anyKey)
        //    Debug.Log("SUCCESS! Input.anyKey is true!");
	}

    void OnGUI()
    {
        if (Event.current.type == EventType.KeyDown && GUI.GetNameOfFocusedControl() == "test")
            Debug.Log("SUCCESS! EventType.KeyDown fired!");
        
        GUI.SetNextControlName("test");
        textAreaString = GUILayout.TextArea(textAreaString);
    }

Okay, so if you check the event before a control uses it, it will work. Wonderful, thank you!

–

Your single comment was the solution to my problems. Thanks RiskyMartin

–

I have a problem still. This allows me to get a event trigger when inside a text box. But what about a toggle button. I'm basically trying to make it my plugin save its settings anytime a button is clicked on the UI.

–