Can't find ObjectField by its name

For some reason, searching for an ObjectField by its name returns null.

Here’s the code:

editEntityNameTextField = root.Q<TextField>("edit-entity-name-textfield");
editEntityNameTextField.value = string.Empty;
if (editEntityNameTextField == null) {
    Debug.LogError("NameText is null");
}

editEntityPrefabObjectField = root.Q<ObjectField>("edit-entity-prefab-objectfield");
// editEntityPrefabObjectField.objectType = typeof(GameObject);
if (editEntityPrefabObjectField == null) {
    Debug.LogError("ObjectField is null");
}

editEntitySaveButton = root.Q<Button>("edit-entity-save-button");
if (editEntitySaveButton == null) {
    Debug.LogError("Button is null");
}

It returns a TextField and a Button without any problems. So, why there are problems with ObjectField?

Here is the hierarchy of UI elements, you can see that the names match:

Console output:
8980663--1235509--upload_2023-4-29_1-12-19.png

Maybe there’s a space at the end of the ObjectField’s name? If you query for it without a name, only with a type, does it still return null?

1 Like

Thanks for pointing me to the right direction. It didn’t find an element by type, so I decided to inspect the type itself.

It turns out the IDE imported ObjectField from UnityEditor.Search.ObjectField namespace (which didn’t show an error, due to the fact that it inherits from the same base type). I changed it to UnityEditor.UIElements.ObjectField and that fixed the problem.

4 Likes

That’s weird, UnityEditor.Search.ObjectField is declared internal, so it shouldn’t be accessible from code. That said… Unity should remove the UXML factories for custom Elements in the Search package; those factories make those elements accessible to users when they shouldn’t be.

1 Like