I am currently working on a Component based game engine written in c++. All components inherit from a component base class. All components in the scene are upcasted into a vector of Components were they can be iterated over and Update()
and such can be called.
I am trying to come up with a communication system for the components. If I have a function called GetComponent<Type>()
Like Unity will I be able to return a component from what is used to be before it was upcasted.
So basically i have an upcasted component and I want to reverse it so it is its original class and then return it via the function(as the class it used to be). Is this possible? If it were possible how would the component know what class it used to be?
Are there any examples of doing this I can learn from?
For this to work you would have to know the original type of the component as it was before adding it to the collection (upcasting it).
So knowing that, it can be done like this (assuming component
is of type Component*
):
SpecificComponent* specific = dynamic_cast<SpecificComponent*>(component);
Not that dynamic_cast can fail => the above can set specific
to nullptr
if the actual component type is not applicable. That, and the fact that it is slower than the other casts make it the most disliked of the C++ casts.
You can also take a look at boost::polymorphic_downcast, which is similar in function. It makes a dynamic_cast
and asserts if it fails in DEBUG mode, but does the faster static_cast
in RELEASE mode.