Hi, I have this MaxHealth variable that has the EditAnywhere specifier. The problem is, should i code the update of the MaxHealth variable value if i change it in the blueprints?
Another problem is, when i start the editor i have the max health (100) but when i restart it, instead of setting health to 100, it remains the value that was in the old instance (so if i end with 50 of health, i’ll restart the next time with 50 of health instead of 100) How do i solve this problem?
If you make any suggestions, please make them compatible with a multiplayer structure, thanks.
The code:
HealthComponent.h
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "HealthComponent.generated.h"
UCLASS(ClassGroup=(Custom), meta=(BlueprintSpawnableComponent))
class ATTRITION_API UHealthComponent : public UActorComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
UHealthComponent();
UFUNCTION(BlueprintPure)
int GetHealth() const { return Health; }
UFUNCTION(BlueprintCallable, Category="Health")
void SetHealth(const int NewHealth) { Health = NewHealth; }
UFUNCTION(BlueprintPure)
int GetMaxHealth() const { return MaxHealth; }
UFUNCTION(BlueprintCallable, Category="Health")
void SetMaxHealth(const int NewMaxHealth) { MaxHealth = NewMaxHealth; }
protected:
UPROPERTY(Replicated)
int Health;
UPROPERTY(Replicated, EditAnywhere, Category="Variable", meta=(AllowPrivateAccess=true))
int MaxHealth;
private:
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty> &OutLifetimeProps) const override;
};
HealthComponent.cpp
#include "Components/HealthComponent.h"
#include "Net/UnrealNetwork.h"
// Sets default values for this component's properties
UHealthComponent::UHealthComponent()
{
PrimaryComponentTick.bCanEverTick = false;
PrimaryComponentTick.bStartWithTickEnabled = false;
SetIsReplicatedByDefault(true);
Health = MaxHealth;
}
void UHealthComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION(UHealthComponent, Health, COND_OwnerOnly);
DOREPLIFETIME(UHealthComponent, MaxHealth)
}