NewObject returns instance with wrong default values

Hey guys,

i want to create UObjects at runtime with different classes that are held in a variable. I need the UObjects to be of blueprint classes (they are data only and inherit from my c++ UClasses), because i set default values in there through the editor.

If i now try to instantiate an object of the class in the gamemode beginPlay()

UBuildableEntity* building = NewObject<UBuildableEntity>(classVarThatIsSetInMyGamemode);

the resulting building object doesn’t actually have the values set in my derived blueprint, but the default values of the c++ parent class (or general default values for this type, idk?). However if set a breakpoint on the line above and inspect the classVarThatIsSetInMyGamemode’s default object the values i set in the blueprint are present.

Can someone help my understand why this happens and how i could fix the issue?
Thanks in advance

https://docs.unrealengine.com/en-US/Engine/Blueprints/TechnicalGuide/Compiler/index.html

The class compilation finishes first and only after it has been compiled, it calls Copy Class Default Object Properties.

More explanation on what a CDO is:

Personally I haven’t dabbled with this too much but if you need the data immediately, I would try to access the CDO for the properties and if that would fail, set up some sort of a callback.

[Workaround below]
Thank you for your answer. While i still don’t understand why the objects aren’t initialized correctly when i generate then with NewObject, i found a workaround.
I now use DuplicateObject instead of NewObject with the default object as the source
UBuildableEntity* entity = DuplicateObject(classVarThatIsSetInMyGamemode->GetDefaultObject(), outer);

I still can’t imagine this is the correct behavior of NewObject, this is why i’ll not mark this as an answer.

They aren’t “initialized properly” because it is a blueprint class. The technical guide on blueprint compiling states that the default values are copied from the CDO after compilation is done, by calling the copy Class Default Object Properties.

NewObject finishes right after the object is created, but before Copy Class Default Object Properties has been called by the created object.

As to why you can get the valid variable values from the next line, that’s because the line is called after the value copying has happened.

DuplicateObject finishes only after the copying is complete, which includes the class variables.

Thank you for clarifying.

If anyone’s also confused about this, the problem is the way NewObject is being called.

UBuildableEntity* building = NewObject<UBuildableEntity>(this, classVarThatIsSetInMyGamemode);

Should work. The first argument is always the outer.