我一直在尝试制作一个类似于Unity的基于组件的系统,但是在C++中.我想知道Unity实现的GetComponent()方法是如何工作的.这是一个非常强大的功能.具体来说,我想知道它用于存储其组件的容器类型.
我在克隆这个函数时需要的两个标准如下.1.我还需要返回任何继承的组件.例如,如果SphereCollider继承Collider,则GetComponent <Collider>()将返回附加到GameObject的SphereCollider,但GetComponent <SphereCollider>()将不返回任何附加的Collider.我需要快速的功能.优选地,它将使用某种散列函数.
对于标准一,我知道我可以使用类似于以下实现的东西
std::vector<Component*> components
template <typename T>
T* GetComponent()
{
for each (Component* c in components)
if (dynamic_cast<T>(*c))
return (T*)c;
return nullptr;
}
Run Code Online (Sandbox Code Playgroud)
但这不符合快速的第二个标准.为此,我知道我可以做这样的事情.
std::unordered_map<type_index, Component*> components
template <typename T>
T* GetComponent()
{
return (T*)components[typeid(T)];
}
Run Code Online (Sandbox Code Playgroud)
但同样,这不符合第一个标准.
如果有人知道某种方法来组合这两个特征,即使它比第二个例子慢一点,我也愿意牺牲一点点.谢谢!