- Home /
Emulating authoritative-client behavior (like NetworkTransform) for SyncVars
As we all know, SyncVar values can only be set on the server, even by components with local authority. When developing an application where the player object controls particular SyncVars, the typical solution is to set their values using Commands. The following code does this with a Color variable:
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Player : NetworkBehaviour {
[SyncVar(hook="MyColorChanged")] Color myColor;
void MyColorChanged(Color next) {
myColor = next;
GetComponent<Renderer>().material.color = next;
}
[ClientCallback]
void Start () {
transform.position = new Vector3 (5, 0, 0);
}
[ClientCallback]
void Update () {
if (isLocalPlayer) {
transform.RotateAround (Vector3.zero, Vector3.up, Time.deltaTime * 100);
Color next = Color.Lerp (Color.red, Color.blue, Time.time / 2.0f % 1.0f);
myColor = next; // Does nothing unless we're the host
CmdSetColor (next);
}
}
[Command]
void CmdSetColor (Color next) {
myColor = next;
}
}
The problem with this approach is that the client player has to wait until the server has received the new SyncVar value and sent an update back before its local value becomes authoritative. This is especially problematic when the value is updated on every frame.
For example, when I run a host and a client with the above Player component, the host's color interpolates smoothly from red to blue, while the client's color stutters irregularly. If I call the SyncVar hook directly (e.g. MyColorChanged(next);
in Update
) the client's color changes more smoothly, but still occasionally flickers when it receives a server update.
However, the NetworkTransform on my player prefab does respect local player authority, and always moves smoothly on the client. My question comes down to this:
Is there any way to emulate the NetworkTransform's syncing behavior on ordinary SyncVars?
I'd appreciate any help I can get on the matter. I've tried a few solutions, and haven't had much luck. In particular, I'm really hoping to get this behavior without introducing too much extra complexity; I know I could do everything with non-SyncVars and some elaborate system of Commands and ClientRPCs, but it seems like overkill for such a simple problem.
Thanks a bunch!
Your answer
Follow this Question
Related Questions
Networking Sync SetActive Not Working 0 Answers
Animating online users sprite 0 Answers
Syncing large amounts of colliders in UNET/Photon? 1 Answer
Unity Editor Crash !!! 0 Answers
Unity Photon Transform Issues 0 Answers