- Home /
How to save/load references to components and prefabs
Our game will require extensive save and load functionality. I've been researching on this site and found tons of useful stuff on serializing basic variables, but nothing I've found quite answers a major concern of mine. As part of our game, the user will be able to construct GameObjects with children and various Components attached. As an example, the player can choose a hull, then add a cockpit and then a turret module. On the turret they can either choose a weapon or a tractor beam, both of which have their own component. The player will have dozens, maybe hundreds of such modules to choose from.
But, how do I go from whatever data I serialize to the prefabs and components I need to call upon to reconstruct the ship? The only way I can think of is to have paired lists. One is list of strings, ints, or floats holding an identifier, and the other holds prefabs. So if the string "hull1" is loaded from the save file, and that matches index 20 of the list of identifiers, then I take the prefab at index 20 of the list of prefabs. However, this seems like a terribly awkward solution. If I needed to change something, then I'd have to manually go through the list and find the entries. And if I needed to remove something, I'll get blank spots in the list or have to manually move something else up.
And for Components, I can't even use a list. The only thing I can think of is a large switch statement in the loading class. (e.g. switch compID { case "Laser" obj.AddComponent(Laser); break;...)
By the way, I have found a plug-in the claims to handle this(http://www.anbsoft.com/middleware/ezs/index.htm), but it's expensive, the site doesn't look trustworthy, and I can't tell if they've updated their software any time recently. It does however, give me hope that a convenient solution is possible.
Answer by asafsitner · Feb 11, 2012 at 12:03 AM
You can load a prefab by name if you know the path to it. Take a look at `Resources.Load`.
You can make your saved names more descriptive so that you can build the correct path from the name alone. Say something along the lines of hulls_tier1_hullA
Then the Load call looks like Resources.Load("/hulls/tier1/hullA");
(splitting the string at '_' char obviously)
No need to load everything into memory and maintain lists and what not. Unless you want to give your player a list of all available modules, and even then you can run several foreach
loops to fetch all available modules of each type (directory), then filter by what they can/can't equip etc.