"Call in Editor" Add Component, Delete Component

Yeah, Epic in unknown reason try to take away from us possibility to use same functionality as in editor (green button Add Component).

First you need to create new class (.h file):

#if WITH_EDITOR
include “SSCSEditor.h”

class CONTROLPOINTSRUNTIME_API SEdit : public SSCSEditor
{
public:
UActorComponent * DoAddComponent (UObject * obj, UClass * ComponentClass);
};
#endif

and .cpp file:

#if WITH_EDITOR
extern UNREALED_API UEditorEngine * GEditor;

UActorComponent * SEdit::DoAddComponent (UObject * obj, UClass * ComponentClass)
{
SelectRoot ();
return PerformComboAddClass (ComponentClass, EComponentCreateAction::SpawnExistingClass, nullptr); /// Protected method need to be Run in Child of SSCSEditor Class
}
#endif

Second you add to your custom actor or blueprint function library this function (.cpp file):

UActorComponent * UBPL::AddComponentInEditor (UObject * BlueprintAsset, UClass * ComponentClass)
{
UActorComponent * Comp = nullptr;

#if WITH_EDITOR
if (GEditor)
{
if (BlueprintAsset)
{
GEditor->SelectActor (dynamic_cast<AActor *>(BlueprintAsset), false, false, false, true); /// Refresh Actor instance - Unselect Actor

  	TSharedPtr<SEdit> sedit;
  	sedit = SAssignNew (sedit, SEdit)
  		.EditorMode (EComponentEditorMode::ActorInstance)
  		.ActorContext (dynamic_cast<AActor *>(BlueprintAsset));
  	Comp = sedit->DoAddComponent (BlueprintAsset, ComponentClass);

  	sedit.Reset ();												/// Remove Shared Pointer Reference. Because it is only one reference, Object "sedit" is destroyed.
  	GEditor->SelectActor (dynamic_cast<AActor *>(BlueprintAsset), true, true, true, true);			/// Refresh Actor instance - Select Actor 
  };

};
#endif

return Comp;
}

This code take me many days to dig into Editor code and many trials.
This code concern UE 5.0.3.
For UE 4.27.2 code different a little.

I think Epic guys should expose this function for programmers in some kind of API. Same as many others functions and do not force developers to use tricks.

@Ldwork_Gamedev wish you good code :slight_smile:

1 Like