Show/Hide VisualElement Dynamically in UI Toolkit - Unity 2022.1.17f1

How To Show And Hide Properties Dynamically using UI Toolkit. For Example, a Boolean “A” has properties “A1” and “A2”. If Boolean “A” is true show the properties but if it is false hide the properties.

I have tried doing it but the inspector doesn’t update the UI, as shown in the GIF:
8630823--1160199--Box Show Hide UI Inspector.gif

The Unity Inspector doesn’t update in accordance with the bool.
Below is my code:

root.Q<VisualElement>("dependantBox").style.display = theBool ? DisplayStyle.Flex : DisplayStyle.None;

This line of code is inside the function “CreateInspectorGUI”. Not Inside the OnInspectorGUI.

I am using UI Toolkit for the inspector.

I have found the Solution. Previously, I was changing the style in CreateInspectorGUI. It is called only when the Inspector is Created (Unlike OnInspectorGUI). This is what caused the glitch.
Now, I register a callback to the Button and change the style inside of it.
like this:

root.Q<Button>("toggler").clicked += () => {
        VisualElement visualElement = root.Q<VisualElement>("visualElement");
        visualElement.style.display = (visualElement.style.display == DisplayStyle.Flex) ? DisplayStyle.None : DisplayStyle.Flex;
};

Now it works perfectly.

1 Like