How to save a GameObject and its randomly generated sprite ?

Hi !

I followed this tutorial (only the first two parts with the swapper.cs script) :

and I have in addition to this swapper.cs, a script that randomly chooses a sprite library (for several body types that don’t go together) to then randomly assign, with the swapper.cs, skins on each element of the body.

And like many people in the comments, i would like to save the final “sprite” and its GameObject to be able to re-instantiate them in another scene for example. No idea what to do !

Thanks !

(I didn’t know where to post for this issue, hope I’m in the right place)

Short answer: save whatever information is necessary to recreate the sprite at runtime.

Load/Save steps:

An excellent discussion of loading/saving in Unity3D by Xarbrough:

Loading/Saving ScriptableObjects by a proxy identifier such as name:

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.

If you want to use PlayerPrefs to save your game, it’s always better to use a JSON-based wrapper such as this one I forked from a fellow named Brett M Johnson on github:

Do not 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.

Thanks for your answer !