GetComponentByClass() Not Working

So I am trying to refactor the Player Controller and the AI Controller to talk to the Aiming Component, but in the TankAIController my GetComponentByClass() statement is not working.

Here is the function were I am defining the AimingComponent variable:

void ATankAIController::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);

auto PlayerTank = Cast<ATank>(GetWorld()->GetFirstPlayerController()->GetPawn());
auto AimComponent = GetControlledTank()->GetControlledTank()->GetComponentByClass<UTankAimingComponent>();

if (PlayerTank)
{
	MoveToActor(PlayerTank, AcceptanceRadius);
	AimComponent.AimAt(PlayerTank->GetActorLocation());
	ControlledTank->Fire(); // TODO Limit fire rate
}

}

In Unreal it gives me an error saying: Error D:\GitHub\01_BattleTank\BattleTank\Source\BattleTank\Private\TankAIController.cpp(23) : error C2275: ‘UTankAimingComponent’: illegal use of this type as an expression

Any suggestions as to what this might mean? I have included the TankAimingComponent.h file in the top of the cpp.

First, you’re using GetControlledTank() twice :stuck_out_tongue:

Second, it takes the class as a parameter, not a template. So it should look something like this: GetComponentByClass(UTankAimingComponent::StaticClass())

You can use FindComponentByClass<UTankAimingComponent>() if you want to use the template. Not sure why both methods are still in the engine.

1 Like

Hey Carson,

Thanks for the reply! I noticed the GetControlledTank() twice myself, but fixing that didn’t resolve the issue. I use the GetComponentByClass method the same way in my PlayerControllerClass and it compiles fine there.

So after staring at my code for quite the while, I discovered that I was using GetComponentByClass<>(), but I should have been using FindComponentByClass<>().

Thanks for the help!

1 Like

Omg. I did the exact same thing. Two years after your post and I am still super grateful it was there lol

Privacy & Terms