How to cast from ACharacter to AActor?

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

You can’t cast to the parent. Character is an actor. You should be able to call all the properties and methods of an actor on the character.

Looks like it doesn’t know what the types are. Try adding #include "GameFramework/Character.h".

4 Likes

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.

Roger that. Maintaining an efficient level of abstraction is always a good priority. GL!

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.

1 Like

This solve my problem, thank you:)

1 Like