Pattern for recreating various gameobjects from Game Save

Is there a pattern or convention to store the “type” of a game object in a save-file, so that it can be re-created easily when loading?

For instance, in my game, I have 8 different enemy types. When loading from a save game, what should I store in order to be able to map them back to the original prefab?

Hello,
I would definitely use JSON, although it comes with several problems, since MonoBehaviour aren’t serializable, you’ll need a serializable class that can transpose into GameObjects upon loading.

Unity is infamous for it’s saving/loading capabilities.\

In your case you need a system that maps “name” or “ID” to a particular prefab.
You save this name or ID in file. with additional data that you need.

The simplest of system is just a list of prefabs and corresponding ID. (id is of your choosing must be unique for every prefab).

1 Like

Ah, I see. Do you have any recommendation on how to do this? Or should my “GameManager” gameobject simply contain a list of available prefabs, or should this be stored somewhere else?

You could store this information in scriptable objects.

I would just associate it by name because a) everything has a name, b) things can be retrieved by names, and c) don’t introduce another identifier to get out of sync.

Load/Save steps:

Don’t use the binary formatter/serializer: it is insecure, it cannot be made secure, and it makes debugging very difficult, plus it actually will NOT prevent people from modifying your save data on their computers.

When loading, you can never re-create a MonoBehaviour or ScriptableObject instance directly from JSON. The reason is they are hybrid C# and native engine objects, and when the JSON package calls new to make one, it cannot make the native engine portion of the object.

Instead you must first create the MonoBehaviour using AddComponent() on a GameObject instance, or use ScriptableObject.CreateInstance() to make your SO, then use the appropriate JSON “populate object” call to fill in its public fields.

1 Like