Unity的GetComponent()如何工作?

Red*_*sty 10 c++ unity-game-engine data-structures

我一直在尝试制作一个类似于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)

但同样,这不符合第一个标准.

如果有人知道某种方法来组合这两个特征,即使它比第二个例子慢一点,我也愿意牺牲一点点.谢谢!

TOM*_*M__ 5

由于我正在编写自己的游戏引擎并采用相同的设计,因此我想分享自己的结果。

总览

我写我自己的RTTI我关心为使用类Components我的GameObject实例。#define通过使用两个宏可以减少键入的数量:CLASS_DECLARATIONCLASS_DEFINITION

CLASS_DECLARATION声明static const std::size_t用于标识class类型(Type)的唯一性,以及virtual声明允许对象class通过调用同名的父类函数(IsClassType)遍历其层次结构的函数。

CLASS_DEFINITION定义了这两件事。即,Type将初始化为class名称的字符串化版本的哈希(使用TO_STRING(x) #x),因此Type比较只是一个int比较,而不是字符串比较。

std::hash<std::string> 是使用的哈希函数,可确保相等的输入产生相等的输出,并且冲突次数接近零。


除了散列冲突的风险较低之外,此实现还具有其他优点:允许用户Component使用这些宏创建自己的类,而不必引用s的某些主include文件enum class或使用typeid(仅提供运行时类型,而不是父类)。


添加组件

像Unity一样,此自定义RTTI简化了Add|Get|RemoveComponent仅指定template类型的调用语法。

AddComponent方法将通用参考可变参数包完美地转发给用户的构造函数。因此,例如,用户定义的Component派生类class CollisionModel可以具有构造函数:

CollisionModel( GameObject * owner, const Vec3 & size, const Vec3 & offset, bool active );
Run Code Online (Sandbox Code Playgroud)

然后稍后用户只需调用:

myGameObject.AddComponent<CollisionModel>(this, Vec3( 10, 10, 10 ), Vec3( 0, 0, 0 ), true );
Run Code Online (Sandbox Code Playgroud)

请注意的显式构造,Vec3因为如果使用推导的initializer-list语法(例如{ 10, 10, 10 }无论Vec3的构造函数声明如何),完善转发都可能无法链接。


此自定义RTTI还解决了该std::unordered_map<std::typeindex,...>解决方案的3个问题:

  1. 即使使用std::tr2::direct_bases最终结果遍历层次结构, 也仍然是映射中相同指针的重复项。
  2. 用户不能添加多个等效类型的组件,除非使用的映射允许/解决冲突而不覆盖,否则会减慢代码的速度。
  3. 不需要不确定和缓慢dynamic_cast,只需直线即可static_cast

获取组件

GetComponent只是使用static const std::size_t Type的的template类型作为参数的virtual bool IsClassType方法和遍历std::vector< std::unique_ptr< Component > >查找的第一个匹配。

我还实现了一种GetComponents方法,该方法可以获取请求类型的所有组件,再次包括从父类获取。

请注意,无论有没有该类的实例,都可以访问该static成员Type

还要注意的TypepublicComponent尽管是POD成员,但为每个派生的类声明,并大写以强调其灵活使用。


RemoveComponent

最后,RemoveComponent使用C++14的init-capture将相同static const std::size_t Typetemplate类型传递给lambda,以便它基本上可以进行相同的向量遍历,这一次是iterator到达第一个匹配元素。


在代码中有一些关于想法的注释,以实现更灵活的实现,更不用说const所有这些版本的版本也可以轻松实现。


代码

类.h

#ifndef TEST_CLASSES_H
#define TEST_CLASSES_H

#include <string>
#include <functional>
#include <vector>
#include <memory>
#include <algorithm>

#define TO_STRING( x ) #x

//****************
// CLASS_DECLARATION
//
// This macro must be included in the declaration of any subclass of Component.
// It declares variables used in type checking.
//****************
#define CLASS_DECLARATION( classname )                                                      \
public:                                                                                     \
    static const std::size_t Type;                                                          \
    virtual bool IsClassType( const std::size_t classType ) const override;                 \

//****************
// CLASS_DEFINITION
// 
// This macro must be included in the class definition to properly initialize 
// variables used in type checking. Take special care to ensure that the 
// proper parentclass is indicated or the run-time type information will be
// incorrect. Only works on single-inheritance RTTI.
//****************
#define CLASS_DEFINITION( parentclass, childclass )                                         \
const std::size_t childclass::Type = std::hash< std::string >()( TO_STRING( childclass ) ); \
bool childclass::IsClassType( const std::size_t classType ) const {                         \
        if ( classType == childclass::Type )                                                \
            return true;                                                                    \
        return parentclass::IsClassType( classType );                                       \
}                                                                                           \

namespace rtti {

//***************
// Component
// base class
//***************
class Component {
public:         

static const std::size_t                    Type;
virtual bool                                IsClassType( const std::size_t classType ) const { 
                                                return classType == Type; 
                                            }

public:

    virtual                                ~Component() = default;
                                            Component( std::string && initialValue ) 
                                                : value( initialValue ) { 
                                            }

public:

    std::string                             value = "uninitialized";
};

//***************
// Collider
//***************
class Collider : public Component {

    CLASS_DECLARATION( Collider )

public:

                                            Collider( std::string && initialValue ) 
                                                : Component( std::move( initialValue ) ) { 
                                            }
};

//***************
// BoxCollider
//***************
class BoxCollider : public Collider {

    CLASS_DECLARATION( BoxCollider )

public:

                                            BoxCollider( std::string && initialValue ) 
                                                : Collider( std::move( initialValue ) ) { 
                                            }
};

//***************
// RenderImage
//***************
class RenderImage : public Component {

    CLASS_DECLARATION( RenderImage )

public:

                                            RenderImage( std::string && initialValue ) 
                                                : Component( std::move( initialValue ) ) { 
                                            }
};

//***************
// GameObject
//***************
class GameObject {
public:

    std::vector< std::unique_ptr< Component > > components;

public:

    template< class ComponentType, typename... Args >
    void                                    AddComponent( Args&&... params );

    template< class ComponentType >
    ComponentType &                         GetComponent();

    template< class ComponentType >
    bool                                    RemoveComponent();

    template< class ComponentType >
    std::vector< ComponentType * >          GetComponents();

    template< class ComponentType >
    int                                     RemoveComponents();
};

//***************
// GameObject::AddComponent
// perfect-forwards all params to the ComponentType constructor with the matching parameter list
// DEBUG: be sure to compare the arguments of this fn to the desired constructor to avoid perfect-forwarding failure cases
// EG: deduced initializer lists, decl-only static const int members, 0|NULL instead of nullptr, overloaded fn names, and bitfields
//***************
template< class ComponentType, typename... Args >
void GameObject::AddComponent( Args&&... params ) {
    components.emplace_back( std::make_unique< ComponentType >( std::forward< Args >( params )... ) );
}

//***************
// GameObject::GetComponent
// returns the first component that matches the template type
// or that is derived from the template type
// EG: if the template type is Component, and components[0] type is BoxCollider
// then components[0] will be returned because it derives from Component
//***************
template< class ComponentType >
ComponentType & GameObject::GetComponent() {
    for ( auto && component : components ) {
        if ( component->IsClassType( ComponentType::Type ) )
            return *static_cast< ComponentType * >( component.get() );
    }

    return *std::unique_ptr< ComponentType >( nullptr );
}

//***************
// GameObject::RemoveComponent
// returns true on successful removal
// returns false if components is empty, or no such component exists
//***************
template< class ComponentType >
bool GameObject::RemoveComponent() {
    if ( components.empty() )
        return false;

    auto & index = std::find_if( components.begin(), 
                                    components.end(), 
                                    [ classType = ComponentType::Type ]( auto & component ) { 
                                    return component->IsClassType( classType ); 
                                    } );

    bool success = index != components.end();

    if ( success )
        components.erase( index );

    return success;
}

//***************
// GameObject::GetComponents
// returns a vector of pointers to the the requested component template type following the same match criteria as GetComponent
// NOTE: the compiler has the option to copy-elide or move-construct componentsOfType into the return value here
// TODO: pass in the number of elements desired (eg: up to 7, or only the first 2) which would allow a std::array return value,
// except there'd need to be a separate fn for getting them *all* if the user doesn't know how many such Components the GameObject has
// TODO: define a GetComponentAt<ComponentType, int>() that can directly grab up to the the n-th component of the requested type
//***************
template< class ComponentType >
std::vector< ComponentType * > GameObject::GetComponents() {
    std::vector< ComponentType * > componentsOfType;

    for ( auto && component : components ) {
        if ( component->IsClassType( ComponentType::Type ) )
            componentsOfType.emplace_back( static_cast< ComponentType * >( component.get() ) );
    }

    return componentsOfType;
}

//***************
// GameObject::RemoveComponents
// returns the number of successful removals, or 0 if none are removed
//***************
template< class ComponentType >
int GameObject::RemoveComponents() {
    if ( components.empty() )
        return 0;

    int numRemoved = 0;
    bool success = false;

    do {
        auto & index = std::find_if( components.begin(), 
                                        components.end(), 
                                        [ classType = ComponentType::Type ]( auto & component ) { 
                                        return component->IsClassType( classType ); 
                                        } );

        success = index != components.end();

        if ( success ) {
            components.erase( index );
            ++numRemoved;
        }
    } while ( success );

    return numRemoved;
}

}      /* rtti */
#endif /* TEST_CLASSES_H */
Run Code Online (Sandbox Code Playgroud)

Classs.cpp

#include "Classes.h"

using namespace rtti;

const std::size_t Component::Type = std::hash<std::string>()(TO_STRING(Component));

CLASS_DEFINITION(Component, Collider)
CLASS_DEFINITION(Collider, BoxCollider)
CLASS_DEFINITION(Component, RenderImage)
Run Code Online (Sandbox Code Playgroud)

main.cpp

#include <iostream>
#include "Classes.h"

#define MORE_CODE 0

int main( int argc, const char * argv ) {

    using namespace rtti;

    GameObject test;

    // AddComponent test
    test.AddComponent< Component >( "Component" );
    test.AddComponent< Collider >( "Collider" );
    test.AddComponent< BoxCollider >( "BoxCollider_A" );
    test.AddComponent< BoxCollider >( "BoxCollider_B" );

#if MORE_CODE
    test.AddComponent< RenderImage >( "RenderImage" );
#endif

    std::cout << "Added:\n------\nComponent\t(1)\nCollider\t(1)\nBoxCollider\t(2)\nRenderImage\t(0)\n\n";

    // GetComponent test
    auto & componentRef     = test.GetComponent< Component >();
    auto & colliderRef      = test.GetComponent< Collider >();
    auto & boxColliderRef1  = test.GetComponent< BoxCollider >();
    auto & boxColliderRef2  = test.GetComponent< BoxCollider >();       // boxColliderB == boxColliderA here because GetComponent only gets the first match in the class hierarchy
    auto & renderImageRef   = test.GetComponent< RenderImage >();       // gets &nullptr with MORE_CODE 0

    std::cout << "Values:\n-------\ncomponentRef:\t\t"  << componentRef.value
              << "\ncolliderRef:\t\t"                   << colliderRef.value    
              << "\nboxColliderRef1:\t"                 << boxColliderRef1.value
              << "\nboxColliderRef2:\t"                 << boxColliderRef2.value
              << "\nrenderImageRef:\t\t"                << ( &renderImageRef != nullptr ? renderImageRef.value : "nullptr" );

    // GetComponents test
    auto allColliders = test.GetComponents< Collider >();
    std::cout << "\n\nThere are (" << allColliders.size() << ") collider components attached to the test GameObject:\n";
    for ( auto && c : allColliders ) {
        std::cout << c->value << '\n';
    }

    // RemoveComponent test
    test.RemoveComponent< BoxCollider >();                              // removes boxColliderA
    auto & boxColliderRef3      = test.GetComponent< BoxCollider >();   // now this is the second BoxCollider "BoxCollider_B"

    std::cout << "\n\nFirst BoxCollider instance removed\nboxColliderRef3:\t" << boxColliderRef3.value << '\n';

#if MORE_CODE
    // RemoveComponent return test
    int removed = 0;
    while ( test.RemoveComponent< Component >() ) {
        ++removed;
    }
#else
    // RemoveComponents test
    int removed = test.RemoveComponents< Component >();
#endif

    std::cout << "\nSuccessfully removed (" << removed << ") components from the test GameObject\n";

    system( "PAUSE" );
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出量

    Added:
    ------
    Component       (1)
    Collider        (1)
    BoxCollider     (2)
    RenderImage     (0)

    Values:
    -------
    componentRef:           Component
    colliderRef:            Collider
    boxColliderRef1:        BoxCollider_A
    boxColliderRef2:        BoxCollider_A
    renderImageRef:         nullptr

    There are (3) collider components attached to the test GameObject:
    Collider
    BoxCollider_A
    BoxCollider_B


    First BoxCollider instance removed
    boxColliderRef3:        BoxCollider_B

    Successfully removed (3) components from the test GameObject
Run Code Online (Sandbox Code Playgroud)

旁注:授予Unity使用Destroy(object)而不是RemoveComponent,但我的版本现在适合我的需求。