Hi, new to Unity here. I’ve worked through an entire book’s worth of tutorials, but none answered my current problem.
I’m making a simple RPG. However, each town is / will be a different scene, and crucially the battle scene itself is a single scene that gets loaded for each battle on a simple battleground.
My question is: How do I keep the player’s inventory, and team of heroes and their current stats ‘alive’ in data, and not deleted? I need all this data, pretty much all the time in every scene, but it seems too extreme to make it all static - I remember from C++ coding that using too many static variables hurts efficiency and is frowned upon. And by the time I’m finished these classes will have a LOT of components and variables.
It appears that using ‘DontDestroyOnLoad()’ on all of my crucial objects that I want to pass between scenes might work, but I’m not positive. Other answers I found on this site were inconclusive.
a) How can I keep the data alive, and
b) Does it make sense to divide different towns into different levels like I’m doing, or is there a better way that lets me get around the data organisation problem.
Thanks in advance.
Statics don’t hurt efficiency: they’re simply stored in some special space created when the game starts, and survive until it finishes. The problem with static variables is more related to the fact that a static variable is unique for all instances - if you declare Player.health as static, for instance, all players will share the same Player.health, thus killing one player kills all of them at once. This makes it difficult to store in static variables info about objects that may have several instances in scene, but it’s ok for single instance objects (the player of a single player game, for instance).
DontDestroyOnLoad offers a more flexible solution, but complicates development because you must not place in scene objects that are supposed to come from previous levels (you don’t want two players in the second level of a single player game, for instance). You can use some development tricks, like instantiating the most important objects if they are not present at Start, but things may become complicated if there are lots of “important objects”. A good compromise is to preserve only info objects - empty objects that hold the needed info in their scripts. You can for instance place the player in every level and make it search for its info object - if not found, create a default one.
Have you tried Playerpref