Generating Visual Elements on Button Click

Hi everyone,

I am working on an inspector UI and I am trying to dynamically generate visual elements on a button click. It works as intended but they disappear when I unselect the GameObject the script is attached to.

Of course, when I add the GenerateVariations code directly in the CreateInspectorGUI the visual elements stay when the gameObject is not active. It seems to be something that is by design but I am really new to this so I would really appreciate help explaining the problem I am having.

[CustomEditor(typeof(Variations))]
public class VariationsExample : Editor
{
    private VisualElement _RootElement;
   
    public void OnEnable()
    {
        _RootElement = new VisualElement(){name ="root"};
        _RootElement.AddToClassList("container");
    }


    public override VisualElement CreateInspectorGUI()
    {
       
        var generateBTN = new Button() {text = "Generate Variations", name = "generate-BTN"};
        generateBTN.AddToClassList("button");
        generateBTN.clickable.clicked += () => GenerateVariations();
       
        _RootElement.Add(generateBTN);
       
        return _RootElement;
   
    }

   
    private void GenerateVariations()
    {
        var test = new Label(){text = "test", name = "test"};
        _RootElement.Add(test);
    }
}

Just to confirm, the generated elements stay even if the gameObject is not active? If that’s the case, this is a bug. But I’m just checking this is not a mistype given your previous paragraph which seems to suggest you do want them to stay but they don’t.

But yes, with the code you posted, the generated Labels will go away if you deselect and reselect your GameObject. This is because your VariationsExample Editor is deserialized and potentially destroyed. If you had some serialized data (like using [SerializeField] on a field), when you reselect your GameObject, that data would be restored. Unfortunately, VisualElements are not serializable so you can’t “remember” a UI hierarchy using Unity’s serialization system.

What you can do is remember the data/state that represents the generated UI. In your simple example, you can store a List<string> of all labels you’ve generated. You can make sure this List<string> is serialized via [SerializeField] List<string> myList; attribute. And then in your CreateInspectorGUI() or even OnEnable(), you can re-generate your Labels.

1 Like

Thank you so much for your reply. There is no bug in this case. the elements don’t stay when the gameObject is not active like how it is supposed. I didn’t know how the editor really works, using Serialized data as you mentioned to store the state of the UI was the way to go. Thank you so much again for taking the time to reply to my beginner question.

1 Like