0
\$\begingroup\$

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;
        }
\$\endgroup\$
5
  • \$\begingroup\$ The PlayerUnit contains a NetworkIdentity, right? \$\endgroup\$
    – Zibelas
    Jun 23 at 12:24
  • \$\begingroup\$ 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. \$\endgroup\$ Jun 23 at 14:23
  • \$\begingroup\$ What exactly needs to be synced? If you want to have transform on it, there is a networkTransform component to handle sync and interpolation. \$\endgroup\$
    – Zibelas
    Jun 23 at 15:20
  • \$\begingroup\$ 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. \$\endgroup\$ Jun 23 at 16:43
  • \$\begingroup\$ 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 \$\endgroup\$
    – Zibelas
    Jun 24 at 7:00

1 Answer 1

2
\$\begingroup\$

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;
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .