I am having trouble casting a Character to an Actor. For example in the following code I should be able to cast from a Character to an Actor, the cast should also always succeed since a Character is an Actor.
ACharacter* character = UGameplayStatics::GetPlayerCharacter(world, 0);
AActor* actor = Cast<AActor>(character);
I even tried casting from a Character to a Pawn, but receive the same errors. When compiling I get the following errors:
A:\Epic\UE_4.18\Engine\Source\Runtime\CoreUObject\Public\Templates/Casts.h(193) : error C2664: ‘APawn *TCastImpl::DoCast(UObject *)’: cannot convert argument 1 from ‘ACharacter *’ to ‘UObject *’
A:\Epic\UE_4.18\Engine\Source\Runtime\CoreUObject\Public\Templates/Casts.h(193) : note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
This fixes the issue I was having. However, I actually managed to fix it with the following code without having to include the headers for Actors or Characters.
ACharacter* character = UGameplayStatics::GetPlayerCharacter(world, 0);
Player = (AActor*)character;
I specifically needed to reference a Character actor as an Actor for an AI controller. It is possible to cast as a parent class, and necessary in many cases.
That’s using standard C typecasting and isn’t recommended in UE4 development. The cast needs the include file so it knows more about the classes than C++ allows. It is best practice to include the proper headers and use the runtime cast nodes.
Plus, if you want to do more than typecast (i.e. call any functions of the class) then you will have to use the include. And if you need to access an interface, you have to use a cast.
One other thing: you could always declare the Player variable as an ACharacter instead of AActor (or even use its actual class because it is derived from ACharacter).
Thanks, I think I will do it that way, I will still need to cast it to an actor for some functions. I don’t want to reference the actual classes for characters in the AI so I can keep my code as self contained as possible and allow it to work with any class.
You don’t need to cast to Actor since your ACharacter is already an Actor. The Actor methods you want to use are already available to your character pointer.