Constructor in custom Movement Component crashes UE5?

I’m creating a custom Movement Component class (a child of UPawnMovementComponent), but after I add a constructor to it in order to initialize member variables, it builds succesfully in Visual Studio but makes Unreal crash instantly after building, and I can only open the project again in unreal if I remove/comment out the constructor and build it again.

Why doesn’t the movement component have a constructor? And why does adding it crashes UE? Is it a bug?
Where should I initialize member variables in a movement component?

When you say it crashes, do you get the crash window with a stack trace? Can you paste the stack trace into the thread.

Can you also paste in the constructor that causes the crash.

1 Like

I just found out the problem wasn’t the constructor itself, but that I was trying to GetWorld() in the constructor. When I removed the call to that function it stopped crashing. I guess it makes sense that GetWorld() wouldn’t work in the constructor.

Constructors are called in a weird fashion in Unreal Engine. There is a special instance of each class called the CDO, and the constructor gets called to create that instance early - so you need to do certain things in the constructor and certain things in other places, like BeginPlay.



Thanks for the link.

After thinking a little I realized it makes a lot of sense that calling “GetWorld()” in the constructor would cause problems, because in the Blueprint editor this would always return null since there is no ‘world’, and the constructor gets called in the editor too. So I called it in BeginPlay instead and it solved the problem.

Right. During CDO construction there is no UWorld yet I believe. An alternative to BeginPlay which occurs very late, is to do stuff in OnConstruct, which is executed in the editor (and possibly prior to cooking, not sure). Having said that, I haven’t been able to get OnConstruct to work well, but your mileage may vary.

1 Like