- Home /
How do I keep references to unique NPCs between scenes?
My game has a large number of NPCs, currently around 500, and among other things each NPC keeps an Affinity score indicating how much he likes each of the other NPCs. Currently I accomplish this with two lists, one List filled with NPCs, and a List containing the Affinity score. This is fine for a cobbled-together prototype, but gameobjects aren't serializeable, and so I can't save my gameobject list between scenes. I've been flirting with the idea of storing all NPC information in an XML database, so each scene would start by instantiating 500 blank NPC prefabs and then filling out their numbers based on the database, but that still doesn't give me a unique identifier. Right now the best solution I've come up with is giving every NPC an ID number, but every time I needed to adjust someone's Affinity I would have to do a GetComponent for every NPC to check the script that has their ID in it, and if multiple NPCs are changing Affinities at once, it could quickly kneecap my performance.
Answer by supericecream · Sep 07, 2014 at 05:17 AM
Since its between scenes, you can do with a static class that holds the two lists. Static members are "persistent" while the program is running, and is as fast as C# can make it go.
Alternatively use some optimization magic for your current method.
Static classes are still lost when the program ter$$anonymous$$ates though, right? Ideally I'm trying to work out a solution that will cover both scene changes and save-quit-reloading.
To have the data existing after the program ter$$anonymous$$ate, you obviously would need to save the data to a persistent location, e.g. a save file. However, static classes are easier on performance, so use that while switching scenes. When you need to save the data, just save the data in the static classes to a local file (Presto!).