Search Unity

How to save a list of instantiated game Objects to a file

Discussion in 'Prefabs' started by killerflip, Sep 13, 2022.

  1. killerflip

    killerflip

    Joined:
    May 26, 2022
    Posts:
    11
    Hey there :)

    I've been using this tutorial to create a save and load system for my game:

    It's basically a save and load system that saves the data to a file in a JSON format.

    It's been quite some time since I've built it, and I just got back into this today. I have some overall questions, that I would be super grateful to get some help for, so it'll get a bit easier for me to dive back into my project.

    I have so far instantiated a list of different prefabs as Game Objects. Once the player clicks on those objects, they get added to another list. I want the objects that are in this list saved and once I change the scene, I want them to be instantiated there.

    Main question is: How can I (best) save a list of different gameObjects to a file, so they can be instantiated in another scene? They do not have to be at the same position they've been before. I thought about maybe instantiating all game Objects in both scenes, setting only the one's to active, that have been saved. But I don't know any way yet, so that the objects, that are set active, match those that have been saved. I would love to get some ideas or feedback :) I have heard about using a dictionary for this cause, but I'm hesitant since I also don't know a way to keep a consistent ID for the instantiated gameObjects.

    Thank you for reading!
     
  2. dynamicbutter

    dynamicbutter

    Joined:
    Jun 11, 2021
    Posts:
    63
    One approach could be to never destroy the objects when you change scenes. You really don't need to go to the trouble of persisting them to file unless they need to survive between games. So check out https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html. You could either call this for every game object or put your game objects inside some kind of instance manager and just make sure the manager isn't destroyed between scenes.
     
    REDACT3D_ likes this.