8

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?

Maik Klein
  • 13,812
  • 20
  • 88
  • 168
  • The way casts tend to work is "try it, did it work?". As Angews answer states, a `dynamic_cast` would be your best bet, followed by a check for a `nullptr`. – OMGtechy Mar 24 '14 at 12:46

1 Answers1

7

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.

Oktalist
  • 13,098
  • 1
  • 38
  • 56