Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

As much as I have feeling that you dont need kind of checks for your player controllers, use IsA function, you dont need to make extra casts.

AController* c = GetController();
if (c->IsA(APlayerController::StaticClass()))
{
    //bla bla
}

As a personal suggesstion check your code design

To add to this question (since its first result on google) if you are using Blueprints you have a pure node called "Class is Child Of" if it would be better in your situation than using a cast.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top