How to "ReplicatedUsing"

How to use ReplicatedUsing and what is the intended behaviour from this?

I am trying to learn on the uses of “ReplicatedUsing” but I have tried it for many days and it is not doing what i have intended it to do. Perhaps i was wrong on the intended use of it.

Basically i have two c++ controllers (Server and Client), each will take their turn to switch on/off a light. So this light should be visible on both the server and client sides. However, regardless of what i have changed, only the light on client side was toggled.



//  actor.h
	UFUNCTION()
	void LightTrigger();

	UPROPERTY( ReplicatedUsing = LightTrigger)
	int32 WhatOn;




// actor.cpp
void AcLightSwitchCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty> & OutLifetimeProps) const {
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	DOREPLIFETIME(AcLightSwitchCharacter, WhatOn);
}

void  AcLightSwitchCharacter::PressButton() {
	WhatOn += 1;
}
void AcLightSwitchCharacter::LightTrigger() {
	if (currentBox) {
		currentBox->toggleLight();
	}
}



The above was just some of the basic code. Could someone please guide a noob like thru this? I have been at this for days, stripping it bare or swapping "netmulticast, server … " and what is not! The strange thing about the ReplicatedUsing is that, the “directed function” aka LightTrigger() for this case, GetPlayerController(this,0) is always the client regardless of whether i am using the server or the client.

OnRep functions aren’t called on dedicated/listen servers, you should call it manually if needed.

Also you should have a ServerPressButton() that will set WhatOn on the server. You should only set replicated values on the server for an unconditional DOREPLIFETIME.

2 Likes

Thanks for the info, i knew that but couldnt get it to work. Finally after some tussle and bustle with codes… I have finally got it working!

To save others from the pain i had, here are the codes…


//  actor.h
	UFUNCTION()
	void LightTrigger();

	UFUNCTION(Server, Reliable, WithValidation)  
	void LightTriggerZ();
	void LightTriggerZ_Implementation();
	bool LightTriggerZ_Validate();

	UPROPERTY( ReplicatedUsing = LightTrigger)
	int32 WhatOn;




// actor.cpp
void AcLightSwitchCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty> & OutLifetimeProps) const {
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	DOREPLIFETIME(AcLightSwitchCharacter, WhatOn);
}

void  AcLightSwitchCharacter::PressButton() { 
	LightTriggerZ();
}

bool AcLightSwitchCharacter::LightTriggerZ_Validate() { return true; }

void AcLightSwitchCharacter::LightTriggerZ_Implementation() {
	WhatOn += 1;
	if (Role == ROLE_Authority)
		LightTrigger();
}

void AcLightSwitchCharacter::LightTrigger() {
	if (currentBox) {
		currentBox->toggleLight();
	}
}

4 Likes

As far as I know the condition of Role == ROLE_Authority in LightTriggerZ_Implementation() will always be true, because the function is only executed in the server.