Hey, I’m looking for ideas on how to save and load multiple instances of objects that can be spawned at runtime.
For example, I have an Inventory actor component that handles all inventory logic, which I attach to various actors like the player, chests, etc. My player has two inventory components—one for the main inventory and another for the hotbar.
The challenge is that I can’t simply store two inventory variables in the SaveGame object for the player and hotbar because chests can be crafted dynamically at runtime, each with its own inventory component. There could be many chests, and I’m unsure how to properly save and load them while ensuring the data is correctly assigned to the right instance.
you’d likely have a level save and a separate player save (because its not level dependent)
for the level iterate over all save game actors and save them to an save struct array (class, transform, savedata)
on load destroy all save game actors and respawn from save data.
This allows you to assign the correct inventory to the correct object, otherwise you’d have to iterate over all objects, compare some ID, load some, spawn any missing objects etc, while ‘spawning’ is slower than ‘loading’ its safer and only happens on a load screen
That’s exactly the problem. For example, my chest has a SaveGame tag, and I save it to a struct containing its class and transform. However, when I load the game and spawn all the saved actors, I have no way of knowing which inventory data belongs to which actor.
One approach could be saving all inventory data in an array within the SaveGame struct. But then, how would I correctly assign that data back to the right actor when loading? I don’t think using a GUID would work because when the saved actors are spawned, they generate new GUIDs, making it impossible to match them with their saved inventory data.
no this wont work, order isnt guaranteed but also you could modify the level or spawn a chest which would break it further. it also doesnt work across different levels.
this is also why ObjectName is unreliable too. what you can do is create a GUID on spawn and save it. this will work but requires some extra steps and is kinda inefficient as you have to constantly iterate over all actors comparing GUIDs.
literally that, so when you save an actor, any actor.
save its class, transform and any class specific data ie inventory array. to a struct. lets call it S_ChestSave for you
on save, getallactorsofclass (maybe with interface) and save all the chests to an array of S_ChestSave.
on load, getallactorsofclass ->DestroyActor (since we’re respawning)
the loop of S_ChestSaveArray->SpawnActorOfClass at saved transform and then set inventory on the new actor.