Variables aren't set on spawned objects

I’m setting a variable on a game object before calling NetworkServer.Spawn() for it. The game object on the server has the correct variable value, but the one spawned on the client just has its default value. What could I be doing wrong?

This is how it’s recommended to be done:

public GameObject treePrefab;

public void Spawn() {
    GameObject tree = (GameObject)Instantiate(treePrefab, transform.position, transform.rotation);
    tree.GetComponent<Tree>().numLeaves = Random.Range(10,200);
    NetworkServer.Spawn(tree);
}

This is how I’ve done it:

[ServerCallback]
public void SpawnEnemy (Enemy prefab, Vector2 pos, float speed) {

    GameObject instance = GameObject.Instantiate (prefab);
    instance.transform.position = pos;
    instance.GetComponent<Enemy> ().speed = speed;
    NetworkServer.Spawn (instance);
  
}

Unity syncs the initial state in the same way it does other network syncing. This means the Enemy component must be a NetworkBehaviour and the speed field must have [SyncVar] for it to be transferred.

3 Likes

Also there is another way. You may set values after spawn.

[ClientRpc]
public void RpcSetSpeed (GameObject Target, float NewSpeed) {
    Target.GetComponent <Enemy> ().speed = NewSpeed;
}

Thank you. Your answer helps me a lot