我有一个标题......
Components.h
namespace ComponentManager
{
void InitializeComponents(std::size_t numComponents);
void AddComponent(const Component& c, std::size_t position);
std::vector<Component> GetComponents();
}
......和实施:
Components.cpp
#include "Components.h"
std::vector<ComponentManager::Component> components;
void ComponentManager::InitializeComponents(std::size_t numComponents)
{
components.resize(numComponents, Component());
}
void ComponentManager::AddComponent(const Component& c, std::size_t pos)
{
components[pos] = c;
}
std::vector<ComponentManager::Component> ComponentManager::GetComponents()
{
return components;
}
在 main.cpp 中,我确保初始化组件向量,并添加几个组件。在调试每个AddComponent(...)调用时,我看到组件实际存储在向量中。但是,当我调用GetComponents()时,返回的向量是不同的,就好像组件从未存储过一样。
我错过了什么?
编辑:添加main.cpp(在main()函数内)
//Inside EntityManager::Initialize(), I call ComponentManager::InitializeComponents()
EntityManager::Initialize(5000);
for (unsigned int i = 0; i < 10; ++i)
{
uint16_t handle = EntityManager::CreatePlayer(static_cast<float>(i), 50.0f * i);
//Inside EntityManager::AddComponent, I call ComponentManager::AddComponent(..)
EntityManager::AddComponent(handle, ComponentManager::POSITION_COMPONENT | ComponentManager::RENDERABLE_COMPONENT);
}
auto components = ComponentManager::GetComponents(); //this vector does not contain the elements that were added.
答案 0 :(得分:1)
最初,这是组件的定义:
union Component
{
PositionComponent positionComponent;
VelocityComponent velocityComponent;
AccelerationComponent accelerationComponent;
RenderableComponent renderableComponent;
Component() {}
~Component() {}
Component(const Component& other) {}
Component& operator=(const Component& other)
{
std::memmove(this, &other, sizeof(other));
return *this;
}
};
添加构造函数和复制构造函数的定义是修复:
union Component
{
PositionComponent positionComponent;
VelocityComponent velocityComponent;
AccelerationComponent accelerationComponent;
RenderableComponent renderableComponent;
Component()
{
std::memset(this, 0, sizeof(Component));
}
~Component() {}
Component(const Component& other)
{
std::memmove(this, &other, sizeof(other));
}
Component& operator=(const Component& other)
{
std::memmove(this, &other, sizeof(other));
return *this;
}
};