How to use Cast<AACtor>(OtherActor)?

Hello again! I try to understand how to use the Cast. UE documentation says that it “Dynamically cast an object type-safely”. But when we need to use Cast and how it works?

Hello Dynamic Casting is a concept used in handling polymorphism. If you are not familiar with this concept I suggest you read in detail about different concepts of Object-Oriented Programming like inheritance and polymorphism. So coming back to the question dynamic casting will help in converting a derived class pointer or reference to a base class pointer, or base class pointer to a derived class pointer (again if you want to know more about the working and usage you should check out c++ concepts as this is related to more c++ instead of Unreal Engine).

1 Like
AActor* SomeActor = nullptr;
APawn* SomePawn = Cast<APawn>(SomeActor);
if (!IsValid(SomePawn)) {
  // actor is invalid or not of type APawn.
1 Like

Usually used to know if some object reference you have up in the class hierarchy is also something down in the hierarchy.

A crude example: Anything that triggers your overlap event is at least an AActor. But for an overlap event you only want it to trigger if the overlapping actor is also a APawn.

So you would get the overlapping actor reference, cast it to a pawn, and then run your logic if the cast is successful.