【发布时间】:2021-06-19 05:23:38
【问题描述】:
我正在编写一个小型 2D 游戏,我目前正在向它添加脚本功能(使用 Lua 或 Python),我偶然发现了这个问题(我认为这将导致我为我的游戏):
我正在使用实体组件系统模式,并且实体的定义由脚本(Lua 表或 Python 字典)提供,因此每当我想构建实体时,我都会运行脚本:
player = {
transformComponent = {
position = {1.0, 2.0, 0.0},
scale = {1.0, 2.0, 1.0}
},
spriteComponent = {
fileName = 'imageFile.png',
numRows = 4,
numCols = 6
}
}
等等。 在 EntityFactory 中,我有一个 EntityFactoryFunctions 映射,以实体名称(例如“玩家”)为键,当我需要构造此类命名实体时调用它们。
现在,每个工厂函数都会读取实体的表(dict)并获取它需要添加到实体中的所有组件的名称。
Entity *CreateEntity(const std::string entityType) // table / dictionary name in script
{
Entity *newEntity = Scene::GetInstance().AddEntity();
return mEntityFactories[entityType](newEntity);
}
typedef Entity *(*EntityFactoryFunction)(Entity*);
std::map<std::string, EntityFactoryFunction> mEntityFactories;
问题是,我的 ECS 使用了 enity.AddComponent
Entity *PlayerFactory(Entity *entity)
{
// read components from Lua table / Python dictionary
// get strings of components' names and store them into vector
Vector<std::string> componentNames;
// create components and add to entity
for (const auto &componentName : componentNames)
{
Component *component = mComponentFactories[componentName](/* pass a reference to component table / dictionary */);
entity->AddComponent<......>(component); // I must know the component type
}
return entity;
}
如何获取要传递给函数模板的组件名称?我需要某种反射系统吗?
【问题讨论】:
-
C++ 中没有反射,所以,是的,你必须自己实现它。 C++ 中没有什么可以为你做这件事。
-
即使我实现了某种反射系统,我如何从与其名称对应的字符串中获取对象的类型?
-
也许 C++ 在这里是错误的工具,因为一旦编译,大部分信息就消失了。在 C++ 中,有一整套编码理念围绕着不带反射的操作而建立。
-
"如何从与其名称对应的字符串中获取对象的类型?" -- 写一个工厂方法。
-
@Luca 这一切都取决于 cpp 的版本。在 cpp20 中,这很容易做到。在早期版本中,将字符串映射到类型有点 hack
标签: c++ templates types reflection scripting