[Question][C++]AI Spawning

Hello, in my game i wanted to try and spawn an AI with a basic AI controller class i made, when i pull the blueprint and put it directly into the world, it will work. But, if i try to spawn the AI by codes, he wont move at all, even though i already set SpawnDefaultController(), it is as if the AI controller wasn’t there in the first place.

Here is how i spawned the AI character:

AICharacter* const Bot = GetWorld()->SpawnActor(BotClass, SpawnLoc, SpawnRot, SpawnParams);
 if(Bot)
 {
    Bot->SpawnDefaultController();
 }

So, the AI will spawn, but will not do anything. Am i doing the AI spawning wrong or is there another way to do it? Any help given is greatly appreciated.

Thanks in advance.

ah found the answer, for some reason if i spawn from codes, the controller will not run BeginPlay(), as an alternative i made some functions to run queries when the AI is spawned.

Dear Hanif,

Probably you are not spawning the correct default controller.

Figure out what the right ai controller should be, for your current AI system,

and add this line to the Constructor for your AICharacter

//Constructor
AIControllerClass = AYourCorrectAIControllerClass::StaticClass();

ex:

If your bot AI code is based off of the Shootergame, find out what the shootergame AI class is

if you are not using any AI setup yet, like Shootergame, then what you are experiencing is the correct behavior

Only shootergame has functional AI system right now, as far as I know

Rama

i did put that in the constructor, i have my own custom AI class, which extends AAIController, which follow everything the shootergame had excluding the blackboard and behaviour tree. My custom AI will work if i put him in world by placing the blueprint directly in world, just not when i spawn him by codes

Can you explain how you did this? Im stuck on the same thing you had

I solved this problem by changing Auto Posses AI option to Placed in World or Spawned in character defaults

6 Likes

Yeah, did this trick for me (: will mark this question as resolved.

If you’re trying to do this all in C++ you also need to set the enum to not just be placed but spawned in.

AIControllerClass = AMyPlayerController::StaticClass();
AutoPossessAI = EAutoPossessAI::PlacedInWorldOrSpawned;

1 Like

Thanks, that solved my problem; For Auto Possess AI, what does it mean by “Placed in World”, any idea?

It means the AI Controller it’s going to possess only the pawns which were placed in the level before running the game. The ones that are being spawn at runtime are not going to be possessed; that’s why the code written by this post’s author was not functioning.

I was spawning the AI character through code and it didn’t work. This solved the problem for me too :smiley: thanks

Thanks a lot!