Search Unity

OnServerAddPlayer SyncList not initialized

Discussion in 'Multiplayer' started by ghoolion, Apr 25, 2017.

  1. ghoolion

    ghoolion

    Joined:
    Apr 25, 2017
    Posts:
    2
    Hey,

    I'm struggeling with the SyncList for some hours now.

    What I am trying to accomplish: Load player items into a SyncList inside the OnServerAddPlayer before AddPlayerForConnection.

    Issue: I'm getting this error on the server side
    Here is the code of the uploaded minimal project.

    Code (CSharp):
    1. public class MyNetworkManager : NetworkManager {
    2.  
    3.     public GameObject StartItemPrefab;
    4.  
    5.     public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) {
    6.         GameObject player = (GameObject)Instantiate(this.playerPrefab, startPositions[0].transform.position, Quaternion.identity);
    7.  
    8.         // Load item
    9.         GameObject item = Instantiate(StartItemPrefab);
    10.         NetworkServer.Spawn(item);
    11.  
    12.         player.GetComponent<Player>().items = new SyncListUInt();
    13.         // Give player the item      
    14.         player.GetComponent<Player>().items.Add(item.GetComponent<NetworkIdentity>().netId.Value);
    15.  
    16.         NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
    17.     }
    18. }
    Code (CSharp):
    1. public class Player : NetworkBehaviour {
    2.  
    3.     public SyncListUInt items = new SyncListUInt();
    4.    
    5.     public override void OnStartClient() {
    6.         Debug.Log("Item " + items[0]);
    7.     }
    8. }
    Thanks in advance for any help!
     

    Attached Files:

  2. Zullar

    Zullar

    Joined:
    May 21, 2013
    Posts:
    651
    You are calling "items = new SyncListUInt();" twice (on lines 12 and 3). Try only calling it on line 3.
     
  3. ghoolion

    ghoolion

    Joined:
    Apr 25, 2017
    Posts:
    2
    Wow, I could have sworn I already tried that. But why does this work? Do you have a clue? I mean, it sounds illogical to me that the "not initialized" error vanishes if I delete the line initializing the error throwing object.

    Anyhow, thanks heaps!
     
  4. Zullar

    Zullar

    Joined:
    May 21, 2013
    Posts:
    651
    you were overwriting items and maybe confusing it. Might want to use properties {get; private set;} to protect yourself from accidentally doing things like that.