GetDefaultObject() with Constructor

Hey, I’m trying to get a struct from another class inside the Constructor of an actor, but it always return Nullptr ingame and i can’t figure out why.

Here is the declaration :

//.h
protected:
         
UPROPERTY(BlueprintReadOnly, Category = "GhostBuilding", meta = (ExposeOnSpawn = true))
	TSubclassOf<ABuilding> Building;

And here the constructor :

AGhostBuilding::AGhostBuilding()
{ 	
	PrimaryActorTick.bCanEverTick = true;    
	if (Building.GetDefaultObject())
	{		
		BuildingInfos = Building.GetDefaultObject()->BuildingInfos;		
	}
}

The “if” statement always return Nullptr, did I missed something? Should I use another method to get Class Defaults?

Constructors are first things that run when you initiate the object, it’s out of control of UE4 as this is how C++ compiler setup machine code, so UE4 don’t even have a chance to inject varbales you imputed in Blueprints to it as well as class defaults set in blueprints when constructor is execute.

UObject and AActor classes have set of events which are called in variues stages of object initiation, you should use one of those, most ealiest one is PostInitProperties

But im not sure if values from ExposeOnSpawn is set at that stage. You can try diffrent events if thats the case:

If you wanted if it to be defaults settable by the user, just copy those from ABuilding

Note that constructors are also first thing that runs when your module is loaded (so in practice when engine is initated) to create CDOs (Class Default Object, thing you trying to access) out of order, so not all CDOs will exist on costructor execution, not to mention defiantly not CDOs generated from blueprints were asset needs to be loaded first or that to happen. So in general accessing CDO in constructor is a bad idea

Thank you for your answer. I tried with PostInitProperties but the CDOs is still Null. But it worked with PreInitializeComponents(), is it safe to call it here? (This is to SetStaticMesh on components)

And do you know where the c++ Constructor is in the Spawning Path of ActorLifecycle?

1 Like