# Synvar not syncing when Instantiating gameObject

I am instantiating a gameObject server-side using the code below. The problem I am facing is that the SyncVar "PlayerUnit" is null on the client, even though I referenced a networked gameObject. Anyone knows what the problem is and how to solve it? Thanks for any help!

[SyncVar]
public GameObject PlayerUnit;

public GameObject PlayerUnitPrefab;

void SpawnUnit()
{
print("Spawning Player Unit");
GameObject newPlayerUnit = Instantiate(PlayerUnitPrefab);
NetworkServer.Spawn(newPlayerUnit);
PlayerUnit = newPlayerUnit;
}

• The PlayerUnit contains a NetworkIdentity, right? Jun 23 at 12:24
• Yes, it has a networkIdentity component and I added it to spawnable prefabs in the networkManager. I think it has something to do with the syncvar update happening before the gameObject is spawned on the client, but I'm not sure. Jun 23 at 14:23
• What exactly needs to be synced? If you want to have transform on it, there is a networkTransform component to handle sync and interpolation. Jun 23 at 15:20
• this method is called on the server by a command on the player object. it creates a player unit in the game world and I want to sync that player unit to the client so that I can use its health, ammo, and other properties in the UI. Jun 23 at 16:43
• If you want to use the changes for UI, maybe you could as well mirror-networking.gitbook.io/docs/guides/synchronization/… just for the parts you need. That way your UI does not need to update them all the time but just when they change Jun 24 at 7:00

I found a workaround using netIds. I think the problem was that when I tried to sync the gameobject, it wasn't spawned yet on the client, so it was null.

[SyncVar]
uint PlayerUnitNetworkID;
GameObject playerUnit;
public GameObject PlayerUnit
{
get
{
if (playerUnit == null)
{
if (PlayerUnitNetworkID == 0)
{
return null;
}
playerUnit = NetworkIdentity.spawned[PlayerUnitNetworkID].gameObject;
}
return playerUnit;
}
}

void SpawnUnit()
{
print("Spawning Player Unit");
GameObject newPlayerUnit = Instantiate(PlayerUnitPrefab);
NetworkServer.Spawn(newPlayerUnit);
playerUnit = newPlayerUnit;
PlayerUnitNetworkID = newPlayerUnit.GetComponent<NetworkIdentity>().netId;
}