Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Variables aren't set on spawned objects

Discussion in 'Multiplayer' started by Deleted User, Nov 8, 2015.

  1. Deleted User

    Deleted User

    Guest

    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:
    Code (CSharp):
    1. public GameObject treePrefab;
    2.  
    3. public void Spawn() {
    4.     GameObject tree = (GameObject)Instantiate(treePrefab, transform.position, transform.rotation);
    5.     tree.GetComponent<Tree>().numLeaves = Random.Range(10,200);
    6.     NetworkServer.Spawn(tree);
    7. }
    This is how I've done it:
    Code (CSharp):
    1. [ServerCallback]
    2. public void SpawnEnemy (Enemy prefab, Vector2 pos, float speed) {
    3.  
    4.     GameObject instance = GameObject.Instantiate (prefab);
    5.     instance.transform.position = pos;
    6.     instance.GetComponent<Enemy> ().speed = speed;
    7.     NetworkServer.Spawn (instance);
    8.  
    9. }
     
  2. mispy

    mispy

    Joined:
    Jul 7, 2014
    Posts:
    2
    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. Artaani

    Artaani

    Joined:
    Aug 5, 2012
    Posts:
    423
    Also there is another way. You may set values after spawn.

    Code (CSharp):
    1. [ClientRpc]
    2. public void RpcSetSpeed (GameObject Target, float NewSpeed) {
    3.     Target.GetComponent <Enemy> ().speed = NewSpeed;
    4. }
     
  4. kaleidosgu

    kaleidosgu

    Joined:
    Jan 8, 2017
    Posts:
    5
    Thank you. Your answer helps me a lot