My abstract implementation for a GameObject
for my components-based game engine is the following:
GameObject
I have been reading about component-based design, and one thing that caught my attention is that linear traversal of arrays is fast due to cache, so this made me decide to use basic arrays to hold entities/game objects.
Now another thing that caught my attention is that some resources separated the components away from a game object. What they did instead is have a map inside an entity manager. The map had game objects as keys and an array of components as values. In this situation, A GameObject
only had an ID.
Is there an advantage (performance and/or design wise) of having a map attaching game objects to components instead of having components inside the GameObject
class?
In addition, GameObject
s are going to pooled (recycled) from a Pool
object, in order to avoid frequent memory allocation.
In most game component system you'll need both arrays and dictionaries (maps).
For linear traversal (ie during update) the array is used to enumerate objects and components.
For lookup by ID, name or other properties one or more dictionaries can be used to find components by the respective type. This is mostly needed where linear search over an array would add up to a noticeable performance penalty.
Furthermore there could be additional arrays storing game objects sorted by components, for instance an array of game objects having a specific component like CombatComponent.
Usually this will be wrapped in a single class allowing you to access components (or game objects) by index, enumerating them, or getting them by some criteria such as ID. The class' implementation can then be updated over time to speed up access to specific components by trading higher memory usage for better performance (ie introducing an additional dictionary to index components by enabled status, or game objects by spatial position).
In short: there are always tradeoffs. It's mainly a matter of convenience and performance to start using additional dictionaries and arrays but it's never an either/or decision.
The default storage implementation should always start with arrays if the objects need to be enumerated sequentially. The main problem with dictionaries is that the order of enumeration may change frame over frame, which has to be avoided in games.