How do I synchronize GameObjects or Components?

For example in World of Warcraft you can target a player and everyone can see who you are targeting.

I could write something like this

Player targetPlayer;
//or
GameObject targetGameObject

Now when the server has a new target I want the client to also know the target, how do I do this?

If I do

[SyncVar]
Player targetPlayer;

The editor just crashes.
*Player is a NetworkBehavior.

[SyncVar]
GameObject targetGameObject;

This will result in targetGameObject to always be null, on the server and on the client.

GameObjects with Networkidentities can be SyncVars. You could also use a NetworkInstanceId (the NetworkBehaviour.netId).

There were some issues with this in earlier release, so be sure to use latest editor patch release.

If you look at the docs for SyncVar (http://docs.unity3d.com/ScriptReference/Networking.SyncVarAttribute.html) there’s a tiny point that I missed on my first SyncVar try too: “Only simple values can be marked as [SyncVars]”. What this means is that SyncVars have to be primatives; classes aren’t supported. You have to build your own syncing for any classes. I can’t say if that’s different for GameObjects. I’m still working through syncing myself, but here’s a great resource I’ve found: https://www.youtube.com/watch?t=49&v=NLnzlwCRjgc. He specifically covers player syncing very well. Good luck!

1 Like

That is what I am currently using, NetworkInstanceId + FindLocalObject.

I am on the latest release 5.1.2p3 and syncvar for GameObjects doesn’t work.

[SyncVar]
public GameObject test;
...

public override void OnStartServer()
{
    test = (GameObject)Instantiate(prefabPlayerCam, prefabPlayerCam.transform.position,
            prefabPlayerCam.transform.rotation);
}

The variable test will always be null on the server and on the client if I mark it with SyncVar.

public GameObject test;
...

public override void OnStartServer()
{

    test = (GameObject)Instantiate(prefabPlayerCam, prefabPlayerCam.transform.position,
            prefabPlayerCam.transform.rotation);
}

By removing SyncVar from the GameObject, the GameObject is now not null on the server but is null on the client as expected.

I think this might be a bug? I am on Windows 10 x64 if that has any relevance.

Edit:

And yes “prefabPlayercam” has a NetworkIdenty script attached.

Edit:

I just forgot to spawn it. It seems to be working now, thanks!