I see one limitation in this solution, though

If we store the components by their class names within the SaveableEntity's dictionary, then we can only have on instance of each ISaveable component.
If there were more than one then the SaveableEntity iterating over the components will overwrite the dictionary entry of the second (or last) one it found.
And on restoring, depending on the exact implementation, it would either only restore state on the first one at all (and keep the others with their default values) or it would set them all to be identical.

Now consider you might have several of them that would have configurable-but-static settings but also dynamic values.
So another thing to consider might be assigning the right set of state values to the right component (iterating over all components on a GameObject should always have them in the order they’re shown in the inspector, so whatever solution one might come up with would require making sure their position in the dictionary is stable (or deriving their key is).

The solution might be to add some counter value to the class’ name to generate the key…

Arguably one should come up with a better setup than having multiple instances of a component on a single object, but there are use-cases where one might need them…

I think one course I did had some sort of AudioManager object where one would put a number of audio tracks on it. But that is probably more a static configuration and wouldn’t need any saving…

One thing that does come to mind where one might use such a thing could be some monster that has a number of tentacles each of which being an instance of a Tentacle component script which might have its own health (and maybe other properties that are dynamic and need saving) as well as some configurable data (for example which one of the possible tentacles it was)…
A better way of doing such a beast would be having each tentacle as a child object on the monster, of course…

Privacy & Terms