I am implementing an Entity Component System and am having trouble when I am attempting to add a Component to an Entity. The structure of doing so is as follows:
Below will find an Entity with an ID of 0, and add a Position component to it.
m_entityManager->addComponentToEntityID(0, ComponentManager::POSITION);
The above is just a helper function to first find the Entity, then it will call the function below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
void EntityManager::addComponentToEntity(std::shared_ptr<Entity> entity, ComponentManager::ComponentType componentType)
{
if (entity != nullptr)
{
switch (componentType)
{
case ComponentManager::POSITION:
entity->addComponent(m_componentManager->getUnassignedPositionComponent());
break;
default:
break;
}
}
}
|
This function will find an unassigned (free, available, not added to an Entity) Position component and return it.
1 2 3 4 5 6 7 8 9 10 11
|
PositionComponent& ComponentManager::getUnassignedPositionComponent()
{
for (unsigned int index = 0; index < m_positionComponentVector.size(); ++index)
{
if (m_positionComponentVector[index].isAssigned() == false)
{
m_positionComponentVector[index].assign();
return m_positionComponentVector[index];
}
}
}
|
Finally, inside of Entity we have this function:
1 2 3 4
|
void Entity::addComponent(Component& component)
{
m_componentVector.push_back(component);
}
|
The Entities are held inside of a vector inside of EntityManager, created as normal objects on the stack. This is the same for the Position components held inside of ComponentManager.
My aim is to keep all Components inside of ComponentManager and systems make request to ComponentManager to process a component in some way. I want to keep pointers or references for each Entity, to the Components that it owns.
My problem is, once Entity::addComponent() is finished, the m_componentVector vector no longer holds the Component that was added to it, like it is falling out of scope. I think the problem is somewhere I am passing a copy instead of a reference? I originally had the parameters as pointers but was playing around trying to fix it.