unity-game-engineuser-interface

Hiding UI in the Unity toolkit


I'm trying to hide my UI in Unity but uiObject.SetActive(false); resets click events and colors for all objects in that Unity UI gameObject.

Before disabling: Before disabling

After disabling and then enabling: After disabling and then enabling How should I be hiding the UI when it isn't needed?

Cheers.


Solution

  • The problem with deactivating the root GameObject (UIDocument) is, that when it is reactivated Unity reloads the UI from the linked VisualTreeAsset => Whatever you have set via code, and whatever button callbacks etc you have set up are gone as you are now dealing with new fresh instances of all the UI elements!

    You rather just want to use VisualElement.visible. Note that this only makes the element(s) invisible and non-interactive but still reserves their space in the layout.

    uiObject.GetComponent<UIDocument>().rootVisualElement.visible = false;
    

    If it is not only about hiding but completely removing from the layouting you would use IStyle.display with DisplayStyle.None instead.

    uiObject.GetComponent<UIDocument>().rootVisualElement.style.display = DisplayStyle.None;
    

    Alternatively you could store the Children of the root visual element (in a list or array) and use RemoveFromHierarchy in order to completely remove them from the hierarchy temporary but keep them around in memory - and Add them again later. But that's a quite aggressive and error prone way of course.