Accessing owner of PlayerState on multiplayer client

…and override virtual void PossessedBy(AController* NewController); so it works on the server too as OnRep is obviously not called :stuck_out_tongue:
So I end up with the following, also using a delegate in case of Team changes during the session.
While you’re here, I’ve also included the color change code that works on the default UE Character. Ps. TeamId is set in the PlayerState from a custom game mode in PostLogin(). Have fun!

void AGameCharacter::PossessedBy(AController* NewController)
{
	Super::PossessedBy(NewController);
	SyncTeamFromPlayerState();
}

void AGameCharacter::OnRep_PlayerState()
{
	Super::OnRep_PlayerState();
	SyncTeamFromPlayerState();
}

void AGameCharacter::SyncTeamFromPlayerState()
{
	if (AVsPlayerState* VsPS = Cast<AVsPlayerState>(GetPlayerState()))
	{
		UpdateTeam(VsPS->GetTeamId());
		VsPS->OnTeamIdChanged.AddDynamic(this, &AGameCharacter::UpdateTeam);
	}
	else
	{
		ensureMsgf(false, TEXT("AUEPhoneGameCharacter expects a AVsPlayerState!"));
	}
}
void AGameCharacter::UpdateTeam(uint8 inTeamID)
{
	if (inTeamID == 0)
	{
		SetTeamColor(FVector(1.f, 0.f, 0.f));
	}
	else if (inTeamID == 1)
	{
		SetTeamColor(FVector(0.f, 0.f, 1.f));
	}
}

void AGameCharacter::SetTeamColor(FVector NewColor)
{
	USkeletalMeshComponent* MeshComponent = Cast<USkeletalMeshComponent>(GetComponentByClass(USkeletalMeshComponent::StaticClass()));
	if (MeshComponent)
	{
		UMaterialInstanceDynamic* MITeam = UMaterialInstanceDynamic::Create(MeshComponent->GetMaterial(0), this);
		MITeam->SetVectorParameterValue(FName(TEXT("BodyColor")), FLinearColor(NewColor));
		MeshComponent->SetMaterial(0, MITeam);
	}
}
1 Like