0
\$\begingroup\$

I have a game where a player can place GameObjects.

I can save/load this GameObjects data with using JSON, for example its position, but I cannot think of a good way to tell my save-file (and my load) what Prefab it needs to instantiate at position X.

How I could this be done in a clever way?

\$\endgroup\$
1
\$\begingroup\$

Several possibilities here. But you could simply have a dictionnary of ID/Prefab saved in a Scriptable Object that would act as a database for you. Then you would just have to save the ID of the prefab you want in your JSON save file. At runtime, when you load your JSON file, you'll end up with a bunch of IDs, and the only thing you'll have to do is to go to your Scriptable Object that contains the ID / Prefab relation and instantiate the right prefab for the given ID.

If you're not familiar with Scriptable Object you can find the documentation here. All it will require is to create a Serializable Class that contains an integer variable for the ID and a transform variable for the Prefab. Then create a simple Scriptable Object with a list of that class you've just wrote. Et voila, your "database" with ID / Prefab relation has been created.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

what you are looking for is called serialization and deserialization.

you want to serialize your environment on save and deserialize it on load.

for this you have lots of options.

you can make it on your own using json or XML that makes everything much more controlled for you or use unity plugins.

what can i suggest is to use put your prefabs in Resources folder as makes you access your prefabs with string using Resources.Load() you just have to make you prefab same name of what you serialized in json or xml the just using any json or xml parser get all of your objects an components.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Do not put your assets in the Resources folder (unless you really know what you are doing). It even says not to use it in Unity's documentation. \$\endgroup\$ – Evorlor Oct 20 '19 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.