Best practice to store cross-level state

Count.Numbers
Sat, 06 Jan 2024 14:42:01 +0000
Programming & Scripting

Hey all,

I’m developing a single player game with many levels. The player transitions between those levels frequently, and both the levels and the players need to preserve state. E.g., door actors need to remember whether they’re open or closed, and the player needs to keep their inventory and stats.

How and where should this state be stored?

Character/Pawn, Player State, and Game State are all out of the question because they are recreated when the level changes.

Game Instance seems to be the only option with a sufficiently long lifecycle.

My current solution does in fact use the Game Instance, but this feels extremely wrong. I have made some wrapper classes around primitives (such as bool) that mirror their value to a TMap in the Game Instance. A DoorActor would have a variable of that type (BoolWrapper), and “SetValue” and “GetValue” would actually read from and write to a TMap which actually resides inside the Game Instance.

While this does work, it seems to violate every principle of software development, such as separation of concerns. Almost all objects need to externalize their variables to one god object. Mirroring the data only on Begin and End Play doesn’t change this substantially. And turning it around – having the Game Instance scrape the object tree and persist relevant data – requires even more knowledge in the Game Instance about things it should know nothing about.

Also, the Game Instance’s lifecycle has the opposite problem now: It’s no longer too short, but it’s now too long: You can’t even create a new one when the player clicks on “New Game”, and rather have to clear and reuse the old one.

I clearly must be missing something. How is this usually done?

4 posts - 2 participants