In an "Entity" class, there is a function that takes in a component typename as an argument, and should return a pointer to that component, if found in the component array. Instead it just returns a copy of the component, not a pointer, despite doing this:
return static_cast<T*>(ptr)
Here is the relevant code:
ECS.h (only the necessary code).
inline ComponentTypeId getUniqueComponentID() {
static ComponentTypeId lastID = 0u;
return lastID ;
}
template <typename T> inline ComponentTypeId getComponentTypeID() noexcept {
static_assert(std::is_base_of<Component, T>::value, "Failed at getComponentTypeID/static_assert() --> ECS/ECS.h");
static const ComponentTypeId typeID = getUniqueComponentID();
return typeID;
}
// Base "Component" class
class Component {
// Code
};
// Base "Entity" class
class Entity {
private:
ComponentArray compArr;
ComponentBitset compBitset;
std::vector<std::unique_ptr<Component>> components;
bool active = true;
public:
Entity() {}
virtual ~Entity() {}
template<typename T> bool hasComponent() const {
// Returns the bitset (bool value)
return compBitset[getComponentTypeID<T>()];
}
template<typename T> T& getComponent() const {
// Returns pointer to component
return *static_cast<T*>(compArr[getComponentTypeID<T>()]);
}
void update() {
// Goes through all the components (for this entity) calls their update method
for(auto &c : components) c->update();
}
void draw() {
// Goes through all the components (for this entity) calls their draw method
for(auto &c : components) c->draw();
}
inline bool isActive() {return active;}
void destroy() {active = false;}
};
CodePudding user response:
Turns out I was returning a reference instead of a pointer in the getComponent() function.
template<typename T> T& getComponent() const {
// Returns pointer to component
return *static_cast<T*>(compArr[getComponentTypeID<T>()]);
}
// Needs to be
template<typename T> T* getComponent() const {
// Returns pointer to component
return static_cast<T*>(compArr[getComponentTypeID<T>()]);
}