Ok I have a problem understanding why people use cast
APlayerController* PlayerController = Cast<APlayerController>(GetController());
while you can get same pointer to player controller with:
APlayerController* PlayerController = GetWorld()->GetFirstPlayerController();
as I know, casting can be quite expensive
another example (from tanks tutorial, tank is a parent class of Turret)
same goes with:
ATank* Tank = Cast<ATank>(GetParentComponent()->GetOwner());
while you can do:
ATank* Tank = ATank::StaticClass()
Answer to first question - usually Actor on a scene doesn’t have controller, so you would generally get NULL pointer. If you call GetWorld()->GetFirstPlayer(), you will always get pointer to player, so it would be a different result.
Second one. Did you actually tried to use it? If you try to call a Tank pointer, for example:
ATank* Tank = ATank::StaticClass();
Tank->ShootThings();
(supposing that ShootThings is not a static method), you will get a crash screen. The reason is simple, StaticClass is UE4 method to check if two objects share same class.
And now - why cast pointers? Suppose I’ll make some class, AMyActor for example, which has some specific public method, for example void AMyActor::SayHello()
. If now I’ll get just a AActor pointer to this actor, I can of course check it’s name, location, rotation etc, but trying to call public method SayHello()
I’ll get a compiling error. BUT - if I’ll cast this AActor*
type pointer to AMyActor*
type, I will be able to use SayHello()
method, because C++ compiler will recognize it as one of internal AMyActor class methods.
Thanks man for detailed answer!
such thing should be explained by unreal documentation, I found similar explanation, but no actually documentation when to use what, a bit frustrating for beginners.