SpawnActor crash

I’m using ue 4.21.2. I want to spawn an actor in AMyPlayerController constructor, but it immediately crashes the editor (won’t even load the project) even though the solution compiles with no error in visual studio.

myplayercontroller.cpp


AMyPlayerController::AMyPlayerController() {
// some stuff
m_some_actor = GetWorld()->SpawnActor<ASomeActor>();
//some more stuff
}

myplayercontroller.h


ASomeActor * m_some_actor;

for reference, the specific SpawnActor overload its using is in World.h. There shouldn’t really be any problems regarding incorrect usage of the method signature


T* SpawnActor( const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters() )
    {
        return CastChecked<T>(SpawnActor(T::StaticClass(), NULL, NULL, SpawnParameters),ECastCheckedType::NullAllowed);
    }

Also confused as to why the editor is crashing on clicking “Compile” to begin with, I can’t even attempt to “play” it. The solution builds with no error in visual studio. It’s one thing if the compilation were to fail and an error is reported in the editor, but for the entire application to crash simply from attempting a compile?

Compiling without errors is not something you can rely on ever, compilers cant understand your code. I have been away from unreal engine for a long time but i do remember that using GetWorld in a constructor is a bad idea, even worse in “editor” mode. First thing i would check is that you actually do get a result from it.

Ok it seems a temporary solution to at least stop the editor from crashing is to add a check


 
 AMyPlayerController::AMyPlayerController() { // some stuff UWorld * world = GetWorld(); if (IsValid(world)) { m_some_actor = GetWorld()->SpawnActor<ASomeActor>(); } //some more stuff } 

This creates more questions:

  1. Why is the editor effectively trying to run the game during/after clicking “Compile”?
  2. Assuming the editor is trying to run, why isn’t GetWorld() returning a valid object? The PlayerController constructor is being called before the UWorld is valid???
  3. Do people wrap every SpawnActor call with a IsValid(world) call? Or should I not be spawning actors in a player controller constructor to begin with?

If my solution compiles without error, I expect the editor to at least open. But this is based on my underlying assumption that the editor isn’t trying to run my game unless I actually hit play, which seems to not be the case.
Why exactly is using GetWorld in a constructor a bad idea?

Unreal creates class default objects from C code.
These objects will also run class constructor.
There’s no valid world for CDOs.

You got the answer to why above, you could use beginplay instead of the constructor.

Ok, but when are these CDOs being constructed? I guess before I even hit play, just from opening the editor?