Agustin0987
Agustin0987

Reputation: 601

Unity UIToolkit TextField events not working

I have the following code, and for some reason when I run it, the logs don't show up in the console (I also attached the VS debugger, and I can confirm the methods are not being called at all). What could I be doing wrong? Am I missing a special setting or something for UIToolkit events to work?

public class Foo : MonoBehaviour
{
    void Start()
    {
        var uiDoc = gameObject.AddComponent<UIDocument>();
        uiDoc.panelSettings = Resources.Load<PanelSettings>("PanelSettings");
        uiDoc.visualTreeAsset = Resources.Load<VisualTreeAsset>("VisualTree");

        var textField = uiDoc.rootVisualElement.Q<TextField>("TextField");
        textField.SetValueWithoutNotify("");
        textField.RegisterValueChangedCallback(OnValChanged);
        textField.RegisterCallback<KeyDownEvent>(OnKeyDown);
    }

    private void OnValChanged(ChangeEvent<string> evt)
    {
        Debug.Log("Hello value changed");
    }

    private void OnKeyDown(KeyDownEvent evt)
    {
        Debug.Log("Hello key down");
    }
}

Some more info:

I know that the GameObject is in the scene and it has a UIDocument component. I know the resources exist, and they can be found and assigned to the UIDocument. The line uiDoc.rootVisualElement.Q<TextField>("TextField"); actually returns the correct TextField element. The TextField has the Is Delay property set to false, so I expect to see the OnValChanged method to be called every time I change a character in the TextField. The PanelSetting object in my project has the Theme Style Sheet assigned to an object called UnityDefaultRuntimeTheme and the TextSettings assigned to an default TextSettings object created in my project.

Also if I store the text field in a variable of the class and log textField.value in the Update function. The log is empty, even though in the UI in the GameView I can see the TextField changing.

It might also be worth mentioning that the line textField.SetValueWithoutNotify("") seems to change the value when looking at it with the debugger attached, but does not change the value in the GameView.

Upvotes: 0

Views: 66

Answers (1)

Agustin0987
Agustin0987

Reputation: 601

Solved it. It seems like the problem was that I was disabling the UIDocument component as soon as it was spawned in the scene with the intention of hidding the UI. I tried to change to disable the GameObject instead, but it seems like even that would break the UI as well (if someone knows why this happens, or if is a bug do let me know please). It seems like the best way to hide the UI is to change the visibility of the root element of the UI document.

Upvotes: 0

Related Questions