Spawning child actors for use in the editor

Given this class (Skipping over UCLASS() and etc. macros for simplicity):

class AContainer : AActor {
	UPROPERTY()
	TArray<AActor*> actors;
}

I want to be able to spawn specific actors and add them to the array. Eg.

AActor* a = GetWorld()->SpawnActor<AActor>();
a->AttachRootComponentToActor(this);
actors.Add(a);

And I want these actors to be editable in the editor. So if I place my AContainer actor onto the stage, it would automatically come with children actors.

Is this possible? I’ve tried putting the spawn code inside the constructor, PostInitializeComponents(), and PostInitProperties(), but I always get a crash upon opening the editor because the level doesn’t yet exist within the world.

I did this in a c++ actor. ( in PostEditChangeProperty )
And then created a blueprint inheriting from this actor, and then simply dropping the actor in the world, then after clicking a boolean, the following code runs, and spawns stuff, even after ue is closed/reopened the spawned actors remain, so it does get serialized as well.

 #if WITH_EDITOR
  UChildActorComponent* ChildActor = NewObject<UChildActorComponent>(GetRootComponent());
  ChildActor->SetMobility(EComponentMobility::Static);
  ChildActor->SetChildActorClass(ClassToSpawn::StaticClass());
  ChildActor->CreateChildActor();
 #endif
1 Like