How can I resolve component types in a way that supports adding new types relatively easily?
Posted
by
John
on Game Development
See other posts from Game Development
or by John
Published on 2014-08-21T19:58:27Z
Indexed on
2014/08/21
22:28 UTC
Read the original article
Hit count: 311
I am trying to build an Entity Component System for an interactive application developed using C++ and OpenGL. My question is quite simple. In my GameObject class I have a collection of Components. I can add and retrieve components.
class GameObject: public Object
{
public:
GameObject(std::string objectName);
~GameObject(void);
Component * AddComponent(std::string name);
Component * AddComponent(Component componentType);
Component * GetComponent (std::string TypeName);
Component * GetComponent (<Component Type Here>);
private:
std::map<std::string,Component*> m_components;
};
I will have a collection of components that inherit from the base Components class. So if I have a meshRenderer component and would like to do the following
GameObject * warship = new GameObject("myLovelyWarship");
MeshRenderer * meshRenderer = warship->AddComponent(MeshRenderer);
or possibly
MeshRenderer * meshRenderer = warship->AddComponent("MeshRenderer");
I could be make a Component Factory like this:
class ComponentFactory
{
public:
static Component * CreateComponent(const std::string &compTyp)
{
if(compTyp == "MeshRenderer")
return new MeshRenderer;
if(compTyp == "Collider")
return new Collider;
return NULL;
}
};
However, I feel like I should not have to keep updating the Component Factory every time I want to create a new custom Component but it is an option. Is there a more proper way to add and retrieve these components? Is standard templates another solution?
© Game Development or respective owner