Jump to content
  • Advertisement
Sign in to follow this  
poigwym

pointer safety in entity component system

This topic is 919 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

the entity class has this:

map<string, Component*>  components;

 

and I have a component :

 

class ComponentA : public Component {};

 

I'm going to get  the ComponentA  using the map ,   Component *cmp =  components["ComponentA"];

and manually cast the  Component* to ComponentA*.   Is this method bad?

 

I want to design a component system like this:

ComponentA *cmpa =  entity.getComponent<ComponentA>();      

if(cmpa) .......

// the function  getComponent<T> will automatically return a component with type T.

how to implement it ???

 

 

Share this post


Link to post
Share on other sites
Advertisement

I agree with what Oberon_Command said in that this isn't a great way to store things, especially if you're interested in performance.

 

Having said that, I do use something similar in one of my projects (not a game), where the individual "entities" hold ownership of a diverse set of components that all inherit from a common base class. The implementation (which requires compiling with RTTI - runtime type information) looks something like this:

    template<typename _T>
    _T *TryGetComponent()
    {
        const std::type_info& r2 = typeid(_T);
        auto result = components.find(std::type_index(r2));
        if (result != components.end())
        {
            return static_cast<_T*>(result->second.get());
        }
        return nullptr;
    }

    template<typename _T>
    void AddComponent(std::unique_ptr<_T> pComponent)
    {
        std::unique_ptr<ResourceComponent> pTemp(pComponent.release());
        const std::type_info& r2 = typeid(_T);
        components[std::type_index(r2)] = std::move(pTemp);
    }

where

std::unordered_map<std::type_index, std::unique_ptr<Component>> components;

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!