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?
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
Python issubclass() This function is used to check whether a class is a subclass of another class.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With