How can I save/load a scene which includes objects that are dynamically created from prefabs

I’m struggling with creating a way to save and load my scene state. Every tutorial I can find about saving/loading only shows how to do something simple such as save/load the player’s stats or save/load a single agent’s state.

My scenes contain some objects that are part of the scene hierarchy in the Unity designer, and some objects that are dynamically created after the game starts. I know how to serialize each object’s data, but I don’t know how to load it back correctly. When I load my game, if an object that I deserialize already has its corresponding Unity game object in the scene, I want that game object to receive the deserialized data. If the corresponding Unity object doesn’t exist in the scene, I want to create it from whatever its prefab was and then load the deserialized data into it. And if an object exists in the scene hierarchy in the Unity designer and it was destroyed during gameplay, I want to remove that object from the scene when I load the game.

This seems like functionality that tons of games need, but I haven’t been able to find a good example or tutorial explaining how to do this. Every way that I can think of involves writing a lot of class-specific save/load methods that would be very error prone and require constant updating any time I add new properties to scripts.

Is there a suggested or common way of achieving this?

1 Like

I was part of a fairly lengthy discussion on this topic here:

Thanks for the link, I read through that thread. It looks like there’s no better way than to manually write out all my saving and loading logic huh? I was afraid of that.