NetworkList object reference not set to an instance of an object

I’m making a local multiplayer game and I’m trying to sync the players connect once someone connects to the game:

    public override void OnNetworkSpawn()
        {
            bool usernameIsLogged = false;
            foreach (PlayerData player in listOfAllPlayers)
            {
                if (player.username.Equals(usernameTextbox.GetComponent<Text>().text))
                {
                    usernameIsLogged = true;
                }
            }
            if (!usernameIsLogged)
            {
                if (IsClient)
                {
                    AddPlayerToListRpc(new PlayerData(listOfAllPlayers.Count, 
                    usernameTextbox.GetComponent<Text>().text, 0, 7));
                }
            }
            loginUIScreen.SetActive(false);    
        }
    
    public void ConnectToGame()
        {
            NetworkManager.StartClient();
        }
    
    public void ConnectToGameAsHost()
        {
            NetworkManager.Singleton.StartHost();
            LoadSaveData();
        }
    
    [Rpc(SendTo.Server)]
    public void AddPlayerToListRpc(PlayerData player)
    {
        listOfAllPlayers = new NetworkList<PlayerData>();
        listOfAllPlayers.Add(player);
        Debug.Log(player.username);
    }

I can connect to the server as a host fine but when I try to connect as a client Unity throws NullReferenceException: Object reference not set to an instance of an object Unity.Netcode.NetworkList`1[T].Add (T item)

Probably because you create a new NetworkList only on the server, in the Server RPC. The client doesn’t run that code therefore the NetworkList on the client side remains null.

It’s best to simply use a field initializer to ensure NetworkList or NetworkVariable are instantiated up front:

private NetworkList<PlayerData> listOfAllPlayers = new();