Delegate Objects/State machine.


I ran into this a few times now and I just used ActorComponents to deal with this.

So my problem is this, I want to keep my code clean and flexible and therefore delegate a few things to child objects. I used ActorComponents for this and it works just fine, but what if I want to change those components via Blueprint Defaults or create some kind of state machine?

At the moment I’m creating a simple state object that needs ticks, so I created an ActorComponent, but how can I make it so that I can swap them out on runtime and/or via DefaultProperties?

Edit: Just adding a simple example.

At the moment I’m working on firemodes for weapons. I want to create the firemode only once and I want them to be tweakable via default properties. So I created a FireModeActorComponent and my initial plan was to create subclasses of that component for Single, Burst, Automatic etc., but as it turned out, I cannot swap them in the default properties which kills my plan right there…

I’ve implemented it the following way for actors.

UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "")
// pass something like AMyActor::StaticClass 
UClass* ActorClass // or TSubclassOf<AMyActor>, and then accessing class like TSubclassOf::Class/Object, not sure about this one

AMyActor* MyActor;

Then simply spawning actor with the specified class, just make sure to cast AMyActor later when needed.
I’m using it for items currently, for example flashlight, i can change default properties and add custom logic via blueprints, if needed, by simple swapping classes in editor.
I’m not sure if it will work for actor components, you would probably need to manually set class and reinitialize component after PCIP initialization, didn’t really touch components yet.
Hope this helps, would like to share bigger code snippets if needed.


thanks for the reply. I acutally already used this approach last night and wanted to write the solution now :stuck_out_tongue:

It was a bit tedious to get it working, but it offers everthing I need. I can now change the FireMode class via Blueprint Defaults and then I just create the UObject in an init function.

BiggestSmile already posted the solution, but I still want to put my code out, for anyone running into similar problems.

I declared a class pointer in my component. This actually shows up as a dropdown in the editor showing every subclass of UFireModeInterface

	UPROPERTY(EditAnywhere, noclear, BlueprintReadWrite, Category = Firemode, meta = (DisplayName = "Firemode Class"))
		TSubclassOf<class UFireModeInterface>  FireModeClass;
	/** Object that handles the actual FireMode */
	UPROPERTY(VisibleAnywhere, Category = Firemode)
		UFireModeInterface* FiremodeObject;

void UFireModeComponent::InitFireMode()
	FiremodeObject = NewObject<UFireModeInterface>(this, FireModeClass);