IndexOutOfRange exception when setting focus on a text field

How does one set input focus on a UIDocument’s text field right after it has finished drawing? Right now I’m attempting to do this in the UI controller’s OnEnable function, but it results in runtime errors (shown below).

public void OnEnable()
{
    var root = this.GetComponent<UIDocument>().rootVisualElement;
    this.usernameField = root.Q<TextField>("username-text");
    this.passwordField = root.Q<TextField>("password-text");
    this.loginButton = root.Q<Button>("login-button");

    this.usernameField.value = "Foo";
    this.usernameField.Focus();
}

The following runtime error occurs with the code above.

UnityEngine.UIElements.TextCoreHandle.GetLineHeight (System.Int32 characterIndex, UnityEngine.UIElements.MeshGenerationContextUtils+TextParams textParams, System.Single textScaling, System.Single pixelPerPoint) (at Library/PackageCache/com.unity.ui@1.0.0-preview.18/Core/Text/TextHandle.cs:175)
UnityEngine.UIElements.TextInputBaseField`1+TextInputBase[TValueType].DrawWithTextSelectionAndCursor (UnityEngine.UIElements.MeshGenerationContext mgc, System.String newText, System.Single pixelsPerPoint) (at Library/PackageCache/com.unity.ui@1.0.0-preview.18/Core/Controls/TextInputFieldBase.cs:759)
UnityEngine.UIElements.TextInputBaseField`1+TextInputBase[TValueType].OnGenerateVisualContent (UnityEngine.UIElements.MeshGenerationContext mgc) (at Library/PackageCache/com.unity.ui@1.0.0-preview.18/Core/Controls/TextInputFieldBase.cs:735)
UnityEngine.UIElements.VisualElement.InvokeGenerateVisualContent (UnityEngine.UIElements.MeshGenerationContext mgc) (at Library/PackageCache/com.unity.ui@1.0.0-preview.18/Core/VisualElement.cs:1464)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)```

I'm able to work around this error by delaying the call to Focus(), but I'd prefer not to have to do that.

I am using Unity Editor 2020.3.20f1 and UI Toolkit package 1.0.0-preview.18. The code sample above is used at runtime (not in the editor).

Hello!

I would expect this to work, so this is probably a bug. Can you please file a new case (Help > Report a Bug…) and paste the issue number in this thread, please?

Bug submitted. Issue # is 1374412

1 Like