Get HUD from controller 'access violation'?

I have read that I can access the HUD through the player controller like so:

RTSMainHud* hud = Cast<RTSMainHud>(GetWorld()->GetFirstPlayerController()->GetHUD());

But I always get an access violation error if I try to call this.

Access violation - code c0000005 (first/second chance not available)

UE4Editor_Engine!UWorld::GetFirstPlayerController() 

My Player Controller is empty I have just a constructor with enabling mouse, enabling mouse click events and mouse over events.

ARTSPlayerController::ARTSPlayerController()
{
	bShowMouseCursor = true;
	bEnableClickEvents = true;
	bEnableMouseOverEvents = true;
}

My HUD is also correctly drawn on screen.

RTSMainHud* hud = Cast(GetWorld()->GetFirstPlayerController()->GetHUD()); Is this code inside a constructor? or in a function called by constructor?

In a Constructor you need to embed the GetWorld() call into this:

if (!HasAnyFlags(RF_ClassDefaultObject | RF_ArchetypeObject)) 
{
    RTSMainHud* hud = Cast(GetWorld()->GetFirstPlayerController()->GetHUD());
}

Alternatively the code can be moved to BeginPlay() or similar functions.

Explanation:

The Editor spawns so called default objects and prototypes for the reflection system (on editor startup as well as on begin gameplay). In these objects the World is not available.

Oh yeah, that’s fixed it. I have now used the method within my BeginPlay function.

Made the answer bit more complete :slight_smile: