1
\$\begingroup\$

I have a very general question about how game classes interact with eachother in a growing RPG game project I'm working on. (Writing it in java/Slick2D, not that is matters because the question is about the concepts)

I have a lot of classes, to name a few, a game class that stores the main game loop that updates all the objects and other classes like player, enemy, HUD, etc. Some variables (mostly ones from Player) are needed in other classes. For example, I need to get the player name, level, xp many times in other classes; my HUD needs the player info to display, I have a class to execute ingame cheat commands such as giving player xp, and my Inventory HUD needs to get the players inventory items to show, etc.

To summarize, what are some general pointers when it comes to getting variables from other classes. Lets say playerXP: my World class declares and holds a Player class, but there are so many other classes, unrelated to the player but still need to get player information. I don't want to make the playerXP public because then some class might accidentally change it. I just need to be able to access player info from many other classes.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The temptation is to make the Character object globally accessible in some way or another. (The Singleton pattern and the Registry pattern come to mind.) Do not follow that temptation.

Instead, pass the Character object explicitly to whatever other objects and methods need it. Make the character stats private, but provide public getter methods that just return properties. That way, other components can read the properties but not change them.

Have a look at http://www.youtube.com/watch?v=-FRm3VPhseI for some background on why this design is better.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .