我正在使用C ++和Lua开发ECS系统。我在寻找正确删除实体及其相关组件(即TransformComponent,GraphicsComponent等)的最佳方法时遇到了麻烦。
创建实体时,会为其赋予其相应的组件,并添加到实体指针向量中,然后还将其组件也添加到其各自的系统中。
我遇到的问题是如何删除实体。例如,我可以轻松地从实体向量中删除其指针实例,但是如何从其各自的系统中删除其每个组件?我所能想到的就是遍历每个系统,并删除其实体指针ID与要删除的实体ID相匹配的任何组件。但是我觉得这样效率很低。每个组件都可以存储指向其父系统的指针吗?
这是实体创建代码:
void State::createEntity(const std::string& type, const std::string& script)
{
mLua.do_file(script);
auto e = new Entity;
e->setType(type);
e->setUID(currentUID++);
sol::table global = mLua[type];
global.for_each([&](sol::object const& key, sol::object const& value)
{
std::string cName = key.as<std::string>();
if (!value.is<sol::function>())
{
sol::table cTable = value.as<sol::table>();
if (cName == "TransformComponent")
{
addComponent<TransformComponent>(e, cTable, transformSystem);
}
}
});
sol::function init = global["init"];
e->init(init);
entities.push_back(e);
}
这是到目前为止的removeEntity函数:
void State::removeEntity(int UID)
{
for (std::vector<Entity*>::iterator it = entities.begin(); it != entities.end(); ++it)
{
if ((*it)->getUID() == UID)
{
entities.erase(it);
break;
}
}
//remove components from systemn?
}
让我知道是否需要澄清, 谢谢!