GetWorld() returning NULL

Hello, im having some problems with a basic setup of an AI controller.

I have setup a custom character and a custom AI Controller class. The character has been placed in the world and has the following code to set their AI controller.

AMyAgent::AMyAgent()
{
    PrimaryActorTick.bCanEverTick = true;
	AIControllerClass = AMyAgentController::StaticClass();
	AMyAgentController* _ai = (AMyAgentController*)AIControllerClass.GetDefaultObject();
	_ai->SetPawn(this);
}

As a simple test my controller is working, when the actor begins play, i call a function from the AI controller called GenerateActorMap(), which simply maps the name of the Actors in the world to their objects for use later.

void AMyAgentController::GenerateActorMap()
{
	for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
	{
		AActor* myactor = *ActorItr;
		FString name = ActorItr->GetName();
		_actorMap[TCHAR_TO_UTF8(*name)] = myactor;
	}
}

However, every time i try to run this code, i get an error that breaks on GetWorld() seemingly returning NULL.

IN ENGINEUTILS.H

......
FActorIteratorState( UWorld* InWorld, TSubclassOf<AActor> InClass ) :
		CurrentWorld( InWorld ),
		Index( -1 ),
		ReachedEnd( false ),
		ConsideredCount( 0 ),
		CurrentActor( NULL ),
		DesiredClass(InClass)
	{
		check(IsInGameThread());
		check(CurrentWorld); //this is the line with the issue
		EObjectFlags ExcludeFlags = RF_ClassDefaultObject|RF_PendingKill;
		GetObjectsOfClass(InClass, ObjectArray, true, ExcludeFlags);
.....

I feel like im missing something fairly simple, my controller should know about a world but i cant understand why it does not, can anyone help me out with this problem?

Hello Jamie453,

Depending on when this function is being called, it could be that the level itself hasn’t been initialized yet. This would cause GetWorld() to return null. The best way to avoid this would be to encapsulate your function’s logic in an if statement checking GetWorld() to see if the level has been initialized yet. This is common practice whenever you deal with referencing the level to avoid such errors.

We haven’t heard from you in a while, Jamie453. Was my previous comment helpful or are you still experiencing this issue? Please let me know if you need any more assistance. I’ll be marking this question as resolved in the meantime for tracking purposes.