重点主要是3个步骤
1. 重载函数 并在beginPlay函数中设置bReplicates=true;
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps)const override;
2.声明变量及notify函数
UPROPERTY(VisibleAnywhere, ReplicatedUsing= OnRep_CurrentLife, BlueprintReadWrite)
float CurrentLife;
UFUNCTION()
void OnRep_CurrentLife();
3.设置同步变量
void AMyPlayerState::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps)const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(AMyPlayerState, TotalLife);
DOREPLIFETIME(AMyPlayerState, CurrentLife);
}
最后提供一份完整的PlayerState 同步变量
.H文件
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerState.h"
#include "MyPlayerState.generated.h"
/**
*
*/
UCLASS()
class TESTFORCPLUSREP_API AMyPlayerState : public APlayerState
{
GENERATED_BODY()
public:
AMyPlayerState();
virtual void BeginPlay() override;
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps)const;
UFUNCTION(Server, Unreliable, WithValidation, BlueprintCallable)
void ApplyDamage(float damage);
bool ApplyDamage_Validate(float damage);
void ApplyDamage_Implementation(float damage);
public:
virtual void Tick(float DeltaSeconds)override;
UPROPERTY(VisibleAnywhere, Replicated, BlueprintReadWrite)
float TotalLife;
UPROPERTY(VisibleAnywhere, ReplicatedUsing= OnRep_CurrentLife, BlueprintReadWrite)
float CurrentLife;
UFUNCTION()
void OnRep_CurrentLife();
};
.CPP文件
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyPlayerState.h"
#include "UnrealNetwork.h"
AMyPlayerState::AMyPlayerState()
{
PrimaryActorTick.bCanEverTick = true;
TotalLife = 100.0f;
CurrentLife = 100.0f;
}
void AMyPlayerState::BeginPlay()
{
Super::BeginPlay();
bReplicates = true;
}
void AMyPlayerState::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps)const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(AMyPlayerState, TotalLife);
DOREPLIFETIME(AMyPlayerState, CurrentLife);
}
// Called every frame
void AMyPlayerState::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AMyPlayerState::OnRep_CurrentLife()
{
UE_LOG(LogTemp, Warning, TEXT("OnRep_CruuentLife"));
}
bool AMyPlayerState::ApplyDamage_Validate(float damage)
{
return true;
}
void AMyPlayerState::ApplyDamage_Implementation(float damage)
{
UE_LOG(LogTemp, Warning, TEXT("ApplyDamage"));
if (damage > CurrentLife)
damage = CurrentLife;
CurrentLife -= damage;
OnRep_CurrentLife();
}