This question has undoubtedly been asked before, but I’m having trouble finding information:
I’d like to save and load information about a prefab that’s been dynamically spawned at runtime- for example: the position of a spawned bird that’s been flying around. I’d like to play my game, spawn the bird, make a save file, restart the game, load my save file, and have the bird exactly where it was when I saved. I’m not sure how to do this:
My usual serialization approach is to give each GO a script with a unique ID (which I generate- not Unity’s InstanceID). This Unique ID is saved with the script as part of the Unity scene. When making a save file at runtime, I serialize these IDs before saving whatever data I need for the script. then, when loading that file, I go through each saved ID, find the matching object in the scene, and load all of it’s data.
That approach works fine for scene objects. But what about dynamically spawned objects, like my bird prefab? I can’t guarantee it’ll have the same ID each time the game is run (again- mine, not the instance ID), so saving its data by ID won’t work.
Any ideas about how to save/load data from dynamically spawned scripts?
Many thanks for any thoughts-
One thing you could do is serialize the data about the gameobject. Not the object itself, but any other properties and information you need to save such as its transform and of course the ID you generated. Then, when you need to reload the object, instantiate a new one (which will get the auto-generated ID) and deserialize your save data… then repopulate the data on the newly spawned GO with the data you deserialized, including the old ID that it had before. Once you serialize the data using something like JSON or BSON or XML, you can either save it to disk or use PlayerPrefs and save the string but with dynamically generated ones you might not know how to find that string again so a file might be your best approach.
My JSON .NET port would work but if all you need is simple serialization, you could use something like JsonObject which is free on the asset store.
I think to serialize is a bloated method requiring more lines of code than it should take to save data. Something like animated birds need to be regulated anyway as you can’t just keep spawning them or performance will drop so you may need a bird limit. A list and a couple of loops may be all you need to add the bird data and remove data if destroyed. Saving whole arrays can be done with array prefs, but it’s just as easy to pack all that data in the list into one long string that can be saved to one line on a .txt file or one player Pref. A simple loop to split and fill the list on start while spawning and positioning the birds back. Easy to expand by simply changing the name of the Pref or what line you want to save a list to.
