0
\$\begingroup\$

I am working on a set of ScriptableObjects that represent base stats for characters in my game. Think Strength, Speed, Intellect, etc. A whole laundry list of em (about 20 stats). I'd like to later be able to reference these specific stats via an enum. Therefore, the easiest way to store them in the object seemed to initially be a Dictionary<StatType, int>. These then get linked to sliders in a custom editor (which works fine).

However, Unity appears to have no idea how to serialize a Dictionary, so between sessions all my finely tuned values get removed.

I need some sort of workaround for this. Either I need another data structure Unity will serialize (but see below), OR I need to find a way to force Unity to serialize my data some other way.

Requirements for an alternate data structure: Integer values should be able to be read and written through reference to the enum value alone. It should be possible to check whether an enum key has been added to the structure or not. It should not allow duplicate enum keys, but duplicate values are fine. Obviously, Unity should be able to serialize it.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ There's a trick I like to use for enum-mapped data structures like this. I show a quick and dirty version of it in this answer. I'd like to make a proper generic version of it so I don't have to repeat the validation boilerplate for each type I want to use it with, but just haven't gotten around to that yet. \$\endgroup\$
    – DMGregory
    Nov 12 '20 at 17:11
  • \$\begingroup\$ @DMGregory Carefully tracking two Lists and applying an indexer to the character class itself does seem the best cleanest option... Leaving this unanswered for now in case someone else thinks of something better, though, especially because I XYd it a bit. \$\endgroup\$
    – Weckar E.
    Nov 13 '20 at 0:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.