Download

C++ Delegate: how to do it?

Hey there,

I have a problem with my code, it doesn’t work.

I have a component where i am making a delegate and declare it.




#include "HealthComponent.generated.h"

DECLARE_DYNAMIC_MULTICAST_DELEGATE(FTestEvent);


UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class SPACEWAR_API UHealthComponent : public UActorComponent
{
    GENERATED_BODY()

public:
    UHealthComponent();


    UPROPERTY(BlueprintAssignable, Category = "Health")
    FTestEvent TestEvent;
}


Than i do broadcast() so that it fires when my function is called.




UHealthComponent::UHealthComponent()
{}

void UHealthComponent::TestHealth()
{
    TestEvent.Broadcast();
}


In my GameMode i am doing AddDynamic so that the broadcast() call will run fires function.



//GameMode.h

UCLASS()
class SPACEWAR_API ASpaceWarGameModeBase : public AGameModeBase
{
GENERATED_BODY()

ASpaceWarGameModeBase();

virtual void BeginPlay() override;
public:

    UFUNCTION()
    void Test();


    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Game Health")
    UHealthComponent *HealthComponents;
}




//GameMode.cpp

ASpaceWarGameModeBase::ASpaceWarGameModeBase()
{
    HealthComponents = CreateDefaultSubobject<UHealthComponent>(TEXT("HealthComponent"));
}


void ASpaceWarGameModeBase::BeginPlay()
{
    Super::BeginPlay();

    HealthComponents->TestEvent.AddDynamic(this, &ASpaceWarGameModeBase::Test);
}



void ASpaceWarGameModeBase::Test()
{
    UE_LOG(LogTemp, Error, TEXT("--TEST--")); //Error only for red color
}


But the message is not being in logged

What i am doing wrong and where is my mistake?

The code seems to be correct. Are you sure you are calling the TestHealth function?

Yes, i put a message in the log before TestEvent.Broadcast()

Are you calling it in BeginPlay() as well? Maybe you are calling it before assigning the function. You can safely bind the function after you’ve created it in the constructor. I’d give this a shot.



ASpaceWarGameModeBase::ASpaceWarGameModeBase()
{
     HealthComponents = CreateDefaultSubobject<UHealthComponent>(TEXT("HealthComponent"));
     HealthComponents->TestEvent.AddDynamic(this, &ASpaceWarGameModeBase::Test);
}


I followed your advice, but nothing has changed. Maybe c++ has some kind of debugging tool like breakpoint in blueprint?

I don’t know how it works, but if i called the Broadcast() in BeginPlay it worked




void UHealthComponent::BeginPlay()
{
    Super::BeginPlay(); 
    TestEvent.Broadcast();
}


After that, the log shows the message --Test–, but when i call this in the function:




void UHealthComponent::ChangeHealth()
{
    TestEvent.Broadcast();
    UE_LOG(LogTemp, Error, TEXT("--HEALTH--"));
}


Only --HEALTH-- appears in the log.
The function does not seem to notice the Broadcast().

Can anyone know what the problem?