I am making a tool that generates UI in the Editor based of some parameters using the UI Toolkit. Everything works fine in the Editor, but when I enter Play Mode, the UI disappears and does not come back even after I have exited Play Mode. In the Editor I can add the UI to the rootVisualElement of a UI Document, and have it display in the Game View, so I am a bit confused as to why the rootVisualElement appears to clear itself permanently every time I hit play.
Everytime you enter Play Mode, a C# Domain Reload happens, which means that all C# objects are destroyed unless they are persistent, like ScriptableObjects or MonoBehaviours.
Visual Elements are regular C# objects and do not survive domain reload. You’ll need to create them in a callback that is called upon every domain reload. The recommendation is to use OnEnable().
Typically, for game UI, you’d do that in a MonoBehaviour added on the same Game Object as the UI Document.
public MyBehaviour : MonoBehaviour
{
public void OnEnable()
{
var document = GetComponent<UIDocument>();
document.rootVisualElement.Add(...);
}
}
2 Likes
Works like a charm.