What is the correct way to procedurally create components in an Editor Tool

Hi everyone,

Hopefully this question is simple enough:

I’m trying to create an editor tool for a project that allows for new components to be added on to an actor outside of the construction script.

The actor exists in the level and the user can press a button to add on components to the object in the level. After finished I need to be able to save this object in the level so that those components remain next time I load that level.

I’m trying to work out what the correct method of instantiating those components is, so far I’ve tried:

		AttachedComponent = NewObject<UAttachedComponent>(this);
	AttachedComponent->CreationMethod = EComponentCreationMethod::Native;
	AttachedComponent->OnComponentCreated();
	AttachedComponent->RegisterComponent();
	AttachedComponent->SetupAttachment(RootComponent);
	AttachedComponent->InitialiseComponent();

for a USceneObject called after PostInitializeComponents. However the components don’t appear on the object, and also don’t save as I get this error: Can-t-Save-graph-is-linked-to-private-objects — ImgBB

I’ve tried using CreateDefaultSubobject, which works fine, but only works during the constructor, which isn’t ideal for my use case since I need to be able to add/remove components during the editor.

Any help or advice would be massively appreciated, as I’m hitting a dead end with this.

Thanks,

Tim

Hi Tim,

Do you want to add the component to just the individual placed instance of the object or to blueprint of the object?

If it’s the blueprint I have done something like this:

void UElgEditorBP_UBlueprint::BlueprintAddComponent(UBlueprint* Blueprint, TSubclassOf<UActorComponent> ComponentClass)
{
	if (Blueprint == nullptr || ComponentClass == nullptr) return;

#if WITH_EDITOR

	// make sure the blueprint type support components before we continue to add one...
	if (!FBlueprintEditorUtils::DoesSupportComponents(Blueprint)) return;

	USimpleConstructionScript* blueprintSCS = Blueprint->SimpleConstructionScript;

	if (USCS_Node* newCompNode = blueprintSCS->CreateNode(ComponentClass, ComponentClass->GetFName()))
	{
		blueprintSCS->AddNode(newCompNode);
	} else {
		UE_LOG(LogTemp, Warning, TEXT("BlueprintAddComponent:: Failed to create an new component node!"))
	}

#endif

}
1 Like