I am currently using Unreal Engine 4 and it seems that I can't avoid some casts.
AController* c = this->GetController();
APlayerController* p = (APlayerController*)c;
Is there a way that I can check if c
is a PlayerController
before I do the cast?
Like a lot of game engines, Unreal Engine is compiled without RTTI for performance reasons, so dynamic_cast
will not work.
Unreal Engine provides its own alternative, simply called Cast
. I can't find any documentation for it right now, but this question describes its use nicely.
AController* c = this->GetController();
APlayerController* p = Cast<APlayerController>(c);
if (p) {
...
}
AController
also has a convenience method CastToPlayerController
which will do the same thing:
AController* c = this->GetController();
APlayerController* p = c->CastToPlayerController();
if (p) {
...
}
If you are sure that c
is always going to be an APlayerController
then CastChecked
is more efficient:
AController* c = this->GetController();
APlayerController* p = CastChecked<APlayerController>(c);
...
In debug builds, this will use Cast
and throw an assert if it would return null; in release builds, it resolves to a fast static_cast
.