[UE5] Is it possible to instantiate a different derived actor component based on enum?

Not sure if this is even possible. I have a base class for an actor component. I have an enum member. You can change it in the editor. I want it to create the derived component based on that enum. I only need this when playing. But if it could switch in the editor, that’d likely be better since the editor would save the instance itself I think, but again, not sure it can do that.

I’m aware of AActor::OnConstruction(), PostEditChangeProperty and AActor::PawnClientRestart(), but I’m not sure if any of these are the right place to put the code. Do I look for the base class, remove it and replace it? Is there an easy way to do this?

Instantiate component only have two ways,one of In constructor CreateDefaultSubobject();,another is dynamic create component.In Beginplay
UYouActorComponent* comp;
comp = NewObject(this);
comp->RegisterComponent();

instantiate component use enum in runtime is workable.

Ok, so I’d need to do this in the Actor then? I’m just using a generic actor right now. I was trying to avoid having to derive it. I’ll give it a shot.

Yes,you may have a enum to store different component type to instantiate.like:
UENUM()
enum class ECompType
{
ECT_HappyComp,
ECT_SadComp,
}

in your actor head file,make this enum a uproperty,then blueprint can edit.
UPROPERTY(EditAnywhere)
ECompType CompType;

in BeginPlay()

switch (CompType)
{
case ECT_HappyComp:
{

UHappyComponent* happyComp = NewObject(this);
happyComp->RegisterComponent();

}

}

RegisterComponent() doesn’t exist. AddInstanceComponent() works. But I have to call BeginPlay() on the new component myself. It does work though.

edit: So I can’t call BeginPlay() myself. It has a check if it’s registered. But I don’t have a RegisterComponent() method.
edit2: FinishAndRegisterComponent() exists and that seems to work fine. It also calls BeginPlay() automatically. I don’t have to do it manually. Thanks again!

RegisterComponent() is a method of Actor Component,you should call it after NewObject.
sample:
Comp = NewObject(this);
Comp->RegisterComponent();

Oh!!! Sorry. For some reason, I was stuck on the idea it has to be registered on the Actor’s side. I’m now using comp->RegisterComponent() and it works great. Thanks for your help!

My pleasure :slightly_smiling_face: