C++ actor component delegate called from blueprint

Hey guys,

My goal is to have an actor component house a delegate that my blueprints can call. this way, it doesn’t matter what the function name is, it is bound and my blueprint can invoke a single delegate name.

I know this is similar to how an interface works but i’m currently trying to find the best scalable solution, where i just add the class, and connect the few bits required. Actor components bring more than what interfaces do.

What i currently have in place is a dynamic delegate in place

// Actor Component.h

#include "HarvestableComponent.generated.h"

UDELEGATE(BlueprintCallable)
DECLARE_DYNAMIC_DELEGATE(FHarvestResourceDelegate);

UCLASS( ClassGroup=(Resources), meta=(BlueprintSpawnableComponent) )
class HOMESTEAD_PROTOTYPE_API UHarvestableComponent : public UActorComponent
{
	GENERATED_BODY()

public:	

	FHarvestResourceDelegate OnHarvestResource;
};
// actor.h
class
{
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Resources, meta=(AllowPrivateAccess = "true"))
	class UHarvestableComponent* resourceComponent; // the actor component


	UFUNCTION(BlueprintCallable)
	void PlotHarvest();
};
// Actor.cpp
#include "Farmplot.h"

AFarmplot::AFarmplot()
{
	ConstructorHelpers::FObjectFinder<UDataTable> plotMatsFinder(TEXT("DataTable'/Game/_Game/Terrain/Resources/FarmplotMeshMaterials.FarmplotMeshMaterials'"));
	plotMats = plotMatsFinder.Object;

 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	resourceComponent = CreateDefaultSubobject<UHarvestableComponent>(TEXT("Harvestable Component"));
	
	auto funName = GET_FUNCTION_NAME_CHECKED(AFarmplot, PlotHarvest);
	resourceComponent->OnHarvestResource.BindUFunction(this, funName);
}

void AFarmplot::PlotHarvest()
{
	GEngine->AddOnScreenDebugMessage(-1, 5, FColor::Red, TEXT("Harvested from actor component by passing in function pointer"));
}

When i open my the blueprint and get an instance of my harvestable component i can’t seem to call my OnHarvestResource delegate.

Can someone show me the errors of my ways?

Okay so i figured it out. In my Actor Component header, i added a function and decorated it with the UFunction macro

void OnHarvest();

Then in my component C++ file, i implemented the function as so:

void UHarvestableComponent::OnHarvest()
{
	OnHarvestResource.ExecuteIfBound();
}

Now in my blueprint, i can get my component and invoke the function Actor Component function OnHarvest. With the bindUFunction in my initial post, it will invoke my harvest.

This allows me to have multiple different actors have their own instance of the actor component, and each binds their own harvest function to their own actor component instance. but i don’t have to do any type checking and branching in the blueprint to call this harvest function. just get the actor component and call the OnHarvest method.

1 Like