Is there a way to keep the UI state when the editor reloads?

Hi everyone, I’ve started using UI toolkit for my current project and from what I’ve observed – UI is being fully reset when the editor reloads (I know that the document is being cleared in OnDisable), e.g. when I change a script, then come back to Unity and all my UI is gone, so I have to re-enter the play mode and repeat every step that got me to the previous state. Is there any way to avoid that?

I’m not talking about working on the UI itself, UI builder serves that purpose. It is really frustrating when, for example I load the game, then from the main menu I initiate a new game, then I’d select a level and finally gameplay UI is then loaded. Now I change one of my scripts related to anything but UI, for example I update player’s speed – when I’m back to the editor – UI is gone, broken and I have to re-enter the play mode.
I’m fairly new to the UI toolkit and the Unity itself, but please tell me that there is a workaround for that?

I was thinking that if there is no built-in way to achieve that I would have to implement some editor-only logic which will be rebuilding all the UI in OnEnable method.

I struggle with the same issue right now but in a different case.
You can apparently get around this to a certain degree by setting viewDataKey values because those will map to a data store which saves the values over domain reloads and sessions (I have an editor window with a few toggles which work this way).

However bound properties apprently need to be rebound after deserialization which is certainly somewhat annoying and I haven’t found a good way to handle this in my editor window.

1 Like

Hi Alex,
is setting viewDataKey (as Fleity suggested) of your UI fixes your problem?

1 Like

It seems the way to do this is rebinding all the UI stuff in OnEnable. So find any references to UI components, add event handlers etc. I think the actual UIElements in the UIDocument are serialized and rebuild automatically, just your references to them are lost. TBH not sure what happens to elements you added to the VisualTree yourself.

1 Like

Thanks for everyone’s suggestions, perhaps I didn’t describe the problem as clear as I thought I did. So, it’s not just the data binding – the whole UI tree is gone. My setup involves one root document which has a MonoBehaviour on it which manages pages (using stack) and after the editor reload all the UI is gone. Apparently same thing happens to the Unity’s DragonCrashers demo, just try to click play button in the editor and then edit any script – as a result UI is broken.
I’ve had a thought that since I have a stack of pages stored on the MonoBehaviour – I’d just try re-create those pages manually, unless there is a better way to do that.