Can I dynamic CreateDefaultSubobject but not just in init function

I want to dynamic create following object:

TSubobjectPtr<USceneComponent> EmptySceneCom = aPCIP->CreateDefaultSubobject<USceneComponent>(this, newName);

But if I did not create the object in init function like following:

APositionIndicator::APositionIndicator(const FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{

}

It will be crashed. does anyway to create the object in other’s function?

I would recommend you to take a look at this:

Object Instance Creation

The thing is that the “DefaultSubobject” is a method with some extra functionality related to the Editor property setup functionality (at least that’s what I use it for). That is: use that method if you want to get the settings you entered at the editor entity inspector.

I usually create my ordinary objects dynamically with something like this:

USceneComponent *Component = ConstructObject<USceneComponent>(USceneComponent::StaticClass(), this, NewName);

Update: in UE 4.8,

ConstructObject has been deprecated in favor of NewObject

CreateDefaultSubobject can only be called within the UObject constructor.

  • Never use CreateDefaultSubobject outside a constructor. It will crash the editor (4.17…)
  • Don’t use: ConstructObject ← Deprecated from 4.9
  • Use NewObject. parent can be “this” if you are creating the object underneath this one.

How to use:

NewObject < classToReturn > (parent, ComponentClassToSpawn*)

Example:

USceneComponent* var = NewObject<USceneComponent>(this,USphereComponent::StaticClass());

Note USceneC is parent type of USphereC.

Other answers here:

NewObject docs:

About objects creation: