I made a simple data script that saves only numbers and the player’s position but I wanted to save another thing, the map because I plan my map to have many changes like destroying objects and things spawning in. Can I do that?
You’ll need to separate the underlying data from the map’s visuals before you can save it. Basically, build a data structure that can represents all the data you need to rebuild the map (or any changes to an existing map) and write that to disk. You’ll of course need to ensure this data is safe to serialize; ergo no references to Unity objects.
All you’re describing is basic loading / saving / persisting, and that is an extremely well-covered subject.
Load/Save steps:
An excellent discussion of loading/saving in Unity3D by Xarbrough:
And another excellent set of notes and considerations by karliss_coldwild:
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. Save data needs to be all entirely plain C# data with no Unity objects in it.
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, so you end up with a defective “dead” Unity 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.
A good summary / survey of the problem space:
Check out the Unity store for add ons. I use “Easy Save” and it really takes a lot of work out of it all.
I was thinking that I could do something like make a new prefab from the saved gameobject and when you load the game it just loads that gameobject instead of saving hundreds of objects and loading it one by one.
You can do anything you like. Be sure to understand what you are doing before you plan grand things in your mind because whatever you design has to work in a Unity context.
See the resources above and make sure you start small with only a few pieces of saved data before wasting weeks on a huge system only to find out that approach won’t interoperate well with your game structure or the Unity engine.
This is after all software engineering, not rearranging living room furniture and wondering if the sofa would look good on that side of the room or not.