Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Null reference exception when adding items to network list from client connected callback?

Discussion in 'Multiplayer' started by ink5, Jul 13, 2023.

  1. ink5


    Sep 23, 2022
    I am running into some issues with the player join callback and network list. This is the only thing that I am loading into the scene right now
    Code (CSharp):
    1. using Unity.Netcode;
    3. public class MyNetworkManager : NetworkManager
    4. {
    6.   private NetworkList<ulong> ids;
    8.   private void Start() {
    9.     ids = new NetworkList<ulong>();
    10.     OnClientConnectedCallback += (ulong playerId) => {
    11.       print(playerId);
    12.       ids.Add(playerId); // this is where I get error
    13.       print(ids.Count);
    14.     };
    15.     StartHost();
    16.   }
    17. }
    The error that I get is
    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. Unity.Netcode.NetworkList`1[T].Add (T item) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.5.1/Runtime/NetworkVariable/Collections/NetworkList.cs:377)
    3. MyNetworkManager.<Start>b__1_0 (System.UInt64 playerId) (at Assets/Scripts/Managers/MyNetworkManager.cs:12)
    4. Unity.Netcode.NetworkConnectionManager.InvokeOnClientConnectedCallback (System.UInt64 clientId) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.5.1/Runtime/Connection/NetworkConnectionManager.cs:46)
    It's longer but I don't think anything below that is necessarily relevant. I think this has got to do with how the callback sets up the network list up to fail since everything runs fine if I just don't add it id (or anything) to the network list.
    Last edited: Jul 13, 2023
  2. cerestorm


    Apr 16, 2020
    To use NetworkList its containing class needs to derive from a NetworkBehaviour, the NetworkManager is actually a MonoBehaviour. Look into creating a separate class for your own additional network management, if you want access to the NetworkManager's callbacks from there you can for example use NetworkManager.Singleton.OnClientConnectedCallback.