Retain prefab instance variables on scene reload

In my game one of my scene objects creates multiple instance of a prefab to fill itself out. (You could imagine my scene object is a tree and it loads lots of leaf GameObject children with different display and animation properties assigned at instantiation, even though this is vastly simplified example)

I’m at the stage where I’m performing lots of small tweaks on implementations to get things perfect, but when I change a value in a script, the scene reloads and each prefab instance has OnDestroy() called -

I don’t fully understand the processes of scene being reloaded due to script change but I understand that Prefab instances variables are “wiped”? (Transforms are being retained, so are Textures etc…).

I’ve tried to use [SerializeField] on the instance field.
I’ve tried using DontDestroyOnLoad(instanceObject);
I’ve tried PrefabUtility.RecordPrefabInstancePropertyModifications(this);

I can’t seem to find any good documentation which really explains scene reload on script change (and how it effects Prefab instances) nor answers on how to mark prefab instances as… “safe” from being destroyed and reloaded.

Are you doing this during play mode?

You can control where a domain reload happens during play mode with this option in Preferences:

If you are intending to domain reload during play mode, a project really needs to be specifically set up for it. And its more effort than its worth.

If you only need to tweak values, consider moving that into a scriptable object, so you can modify them in play mode and have those changes persist.

Hi Spiney, thanks for the reply.

Good to know about the Recompile control - It’s basically what I’m doing right now.

I’m definitely masochist enough to set my project up “right” to make sure things reload correctly - It definitely helps me learn and heads off future maintenance headaches.

For instance, I’m wondering if this is caused by some of my objects not Serializing - which I’ll need for save/load of the game later on anyway.

The changes I’m making right now are largely in VisualElements in UI Toolkit - which is a pig to work with even when doing it raw in code :smiley:

(If you could point me towards the “specific setup” required I’d really appreciate it)