UObject is still nullptr after being initialized in constructor

Hello o/

I have two C++ classes (let say A and B class) which inherit from the same C++ parent class (let say AZ), which contains a custom Data variable (UMyData, which just inherit from UObject)

In each constructor of those 2 C++ classes, I’m making a new instance of this Data by calling NewObject function, like below.

AA::AA()
{
   Data = NewObject<UMyData>();
   //...
}

AB::AB()
{
   Data = NewObject<UMyData>();
   //...
}

AA class doesn’t have any BP inheriting from it. It’s being spawned in the Scene in full C++ with SpawnActor function, and it works perfectly.

Now, AB class has a BP child class (let say BP_AB), and this BP child class is being spawned in the world from another BP with the SpawnActor node. And… my Data variable is nullptr/not valid even just after being spawned.
I just don’t understand why. The C++ constructor is called, the BP constructor script is empty, and Data is NOT nullptr in the C++ constructor function. But once we leave the constructor function, it’s back to nullptr and I don’t have any clue why.

BP spawn call

C++ constructor

Result :

Capture d'écran 2023-11-20 103912

AB is an already existing BP class I reparent from AActor to my C++ AZ class (which inherit at some point from AActor, so no problem here), and there was no conflict what so ever.

For now I dodge the problem by setting the Data variable in the BeginPlay function, but it makes no sense from my pov that it works for AA C++ only class and doesn’t for BP_AB (BP_SplineActor in the screenshots)

If anyone has a clue regarding why it behaves like that…

No idea precisely why it behaves like that, but generally in constructors you should be using CreateDefaultSubobject rather than NewObject.

I wouldn’t be surprised if your blueprint also became slightly corrupted because of this, so you might also want to rename the variable to Data2 or something, at least temporarily, until the BP works and is resaved.

1 Like

Well, thank you ! A call to CreateDefaultSubobject instead fixed my problem. The bahavior must surely be different between BP and pure C++ regarding my case.

I forgot about this function because it annoyed me when I wanted to initialiaze a BP Component within the constructor, as the only way was to hardcode the class path in order to be able to use it in the constructor.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.