Code design when replacing one object with another

Hi!

Im looking for thoughts on OOP/code-design regarding a specific situation. I’m developing a game currently that will have items on each level in an “item bar” on the top of the screen. The player can drag items from the bar into the “game world”. The items can of course have different types and properties.

The different main approaches I can think of is (I will rank them from my least favorite to favorite):

A: Place the “real” objects (that’s used in the game world) inside the item bar and have them adapt to the item bar (maybe shrink etc + have a state which is “in itembar/in game world”). When the player drags the object into the game world the object simply changes state.

B. Have a class “BarItem” which populates the Item Bar. Every BarItem would have to have some information about what “real object” it represent (an enum for example). When the player drags the item into the game world the BarItem (or some other class) spawns the “real” game object. The problem with this solution is that it can end up being a lot of switch statements which all need to be updated if I add a new entity.

C. Almost as alternative B, but instead of an enum I attach the “real object” to the BarItem, and the BarItem activates the real object when it is dragged into the game world.

If you dont understand maybe I can try to explain it better - but the question is basically: How to handle conversions between different objects that represent the same “object”? For example; when you choose to play as Mario in the menu in Mario Cart the Mario that is displayed in the menu is obviously not the same object that is going to get spawn into the game world. They represent the same “object” but will be of very different classes.

Honestly, the item on the bar would be a class that holds references to the barItem itself. It would need to know what sprite to display, name, anything dealing with the item on the bar. Then, it would have a reference to an item id. This item id would be used when it’s dragged into the scene. Whatever class handles spawning the item could grab the id and use it to spawn the item. You shouldn’t need a big switch statement. You should be able to handle this with a simple method or two to fetch what you need to spawn. There are different ways to set this up so it works like it should without creating a complex system that you have to micromanage.

1 Like