Download

Proper cast from U-type to F-type?

Hello all,

I have a couple custom actors which are derived from AActor. They are also derived from a non UClass which I will call “FMyClass”.

I want to use a dynamic cast from “AActor” to “FMyClass” and I have tried the following:



AActor* actor...
FMyClass* myClass = Cast<FMyClass>(actor);


However it seems Cast only works on UObjects as it needs the “StaticClass” function.

So I tried dynamic_cast instead:



AActor* actor...
FMyClass* myClass = dynamic_cast<FMyClass*>(actor);


This time around I get the error:

‘dynamic_cast’ used on polymorphic type ‘AActor’ with /GR-; unpredictable behavior may result

Anybody knows how I am supposed to properly cast it? Or perhaps I should find a different approach?

Thanks

Interesting question. I assume you have multiple derived types and you don’t know which one your actor is? And it’s not possible for the actor types to derive from a common actor base class, which itself derives from FMyClass?
I doubt UE4 has inbuilt support for this since it disables RTTI (hence the dynamic_cast error) and replaces it with its own version that relies on the reflection system, so knows nothing about non-reflected types.

Off the top of my head, the only way I can see to do this would be to use a UE4 interface, with an interface method that returns a pointer to FMyClass. You’d just override the method on each derived type with a simple “return this;”.

Edit: I’ve never needed to do this. I think there’s a good chance you could find a different way of structuring things to just avoid the limitation.

The interface route was one way I had thought of doing it. The other is to use an actor component with the implementation stuff instead although I would’ve liked to have it as part of the actor itself.
I would’ve liked to have had common base actor class unfortunately the actors that I am deriving from are AActor, APawn and ACharacter.

Well I will probably be using one of the other approaches instead. Thanks for the comment:)