Download

Struct is reset when passed through interface?

I’m trying to pass a struct through an interface, but all it’s data gets reset. Not sure if I’m doing something wrong here.

//The Struct


USTRUCT(BlueprintType)
struct FDamageParams
{
    GENERATED_BODY()
public:
    float **PrevHealth**;
   // other params
};

//ControllerInterface.h


UFUNCTION(BlueprintCallable, BlueprintNativeEvent) void Damage(FDamageParams **params**);

//Calling the interface on the controller when pawn damage is taken


**params.PrevHealth** = CurHealth;
CurHealth -= 5;

IControllerInterface::Execute_Damage(GetController(), **params**);

//Receiving the damage on the controller


void AHeroController::Damage_Implementation(FDamageParams **params**) {
***// params.PrevHealth, and all values inside params are reset to 0!***
    HealthBar_ins->SetScalarParameterValue("Prev", **params.PrevHealth**);
    HealthBar_ins->SetScalarParameterValue("Cur", Pawn->CurHealth);
}


The struct works fine to be passed all around, but the moment it passes through an interface function it gets completely reset.
How can I solve this?

Thanks!

You are passing the FDamageParams variable by value. When you pass by value, the compiler makes a copy of the variable with default data.

In this case, you want to pass by reference:



void AHeroController::Damage_Implementation(FDamageParams &params);


I strongly suggest you read up on the difference between passing by value and passing by reference.

That’s not how passing by value works anywhere. It should copy the struct with the values that are set into. It doesn’t (or shouldn’t) copy “with default data”.

I figured out the problem:


USTRUCT(BlueprintType)
 struct FDamageParams {    
GENERATED_BODY()
public:    
**UPROPERTY() float PrevHealth;**    
// other params
};

Making it a UPROPERTY (and restarting unreal) allowed the property to persist through the interface.

But thanks for the info guys, I didn’t even think about passing as a reference, that would have most likely worked as well!
Might actually go back someday and change many things into references where relevant.

Edit: Turns out I added UPROPERTY on a different value, NOT on PrevHealth, even though it randomly started working the next day. Just Unreal being Unreal I guess.

You are completely right. I misspoke! Apologies. I should have just suggested passing by reference.

Thanks for keeping me honest!