UE4 c++ 变量RepNotify

重点主要是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();
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值