How to use [SyncVar] on NetworkBehaviour subclasses?

I would like to sync up a class member that contains a reference to another game object of the same NetworkBehaviour subclass. Usually, it’s for keeping track of where the enemy is, and I want to keep a reference to it.

Here’s the following code:

public class Foo : NetworkBehaviour {
    [SyncVar]
    public Foo enemy;
}

But just that code itself crashes Unity editor. Does that mean you can’t keep track of an enemy unit in a multiplayer game? Are there any other workarounds?

Bug report Case 735614, for reference.

The docs say syncvars can be primitive types or structs, I didn’t see a mention of GameObject or classes. There is edit or build time checking coming in 5.2:

You are probably safer using a weak reference that has to be looked up, like the netId from the NetworkIdentity of the enemy for example and then looking up like so: Can you search for GameObjects by NetworkIdentity? - Unity Engine - Unity Discussions

Does that mean I have to look it up all the time whenever the Foo object is updated? And have to manually set them to the same object for both the server and the client?

you could have a syncvar int that is the netid, look it up when it is set the first time in a hook, then cache the reference to the gameobject. Just realize that it is possible that your cached gameobject reference may go null if that object is destroyed, but that should be under your control.

I’ll go ahead and try this. If I have other issues, I’ll ask around. Thanks.