How to Get AI Controller in C++

I’ve just started converting my BPs to C++ today and I know close to nothing how Unreal’s C++ works. Right now I’m converting this piece of BP:


I’ve been trying to figure how to get AI controller for an hour now. Documentation and google can’t halp me either

image

It depends. “Get AIController” is a bit of a special function as in it’s a global utility function, rather than being part of a specific class.

This “utility” function takes an “Actor” as input and adapts based on what you throw at it. If you give it a pawn, it’ll find the controller of the pawn. If you give it a controller, it’ll test the controller itself. That’s all it does, really. This utility function is located in the AIBlueprintHelperLibrary, and you can call it as is from c++.

//.h
UCLASS()
class AMyActor : public AActor
{
    GENERATED_BODY()
public:

    UPROPERTY()
    TArray<AActor*> Enemies;

    virtual void NotifyActorBeginOverlap(AActor* OtherActor) override;
};

//.cpp
void AMyActor::NotifyActorBeginOverlap(AActor* OtherActor)
{
    Super::NotifyActorBeginOverlap(OtherActor);

    for (AActor* Enemy : Enemies)
    {
        AAIController* C = UAIBlueprintHelperLibrary::GetAIController(Enemy);
        if (C && C->GetAIPerceptionComponent())
        {
            C->GetAIPerceptionComponent()->SetSenseEnabled(UAISense_Sight::StaticClass(), false);
        }
    }
}

If your array of “Enemies” contain pawns, the more “standard” approach would be to use Pawn → GetController → Cast to AIController.
In c++ this would translate to

TArray<APawn*> Enemies;
for (APawn* Enemy : Enemies)
{
    AAIController* C = Enemy->GetController<AAIController>();
    if (C)
       //...
}
1 Like

Assuming your enemies are pawns (or characters, which anyway inherit from pawns) you use GetController, and cast its result to a generic AIController or to your specific AIController. Supposing it’s the former (in this example we’re just enabling their hearing sense):

#include "AIController.h"
#include "Perception/AIPerceptionComponent.h"
 #include "AIModule/Classes/Perception/AISense_Hearing.h"

// your array it's something like TArray<APawn*> myEnemiesArray 

for (auto& Enemy : myEnemiesArray)
			{
				AController* myEnemyController = Enemy->GetController();
				AAIController* myAIEnemyController;
				if (myEnemyController)
					myAIEnemyController = Cast<AAIController>(myEnemyController);
				if (myAIEnemyController)
				{
					myAIEnemyController->GetPerceptionComponent()->SetSenseEnabled(UAISense_Hearing::StaticClass(), true);
					//whatever other logic you need
				}
			}

Hope that helps!

Cheers,
f

1 Like

In File [NameYourProject].build.cs needs to add:
PublicDependencyModuleNames.AddRange(new string[] { “Core”, “CoreUObject”, “Engine”, “InputCore”, “AIModule” });


And needs to adds #include "AIController.h" in your .cpp file

1 Like