"InvalidCastException: Specified cast is not valid." While making custom network manager

I am trying to make a custom network manager for my multiplayer game. What I want to do is have the first player spawn in as the prefab “legs,” and the second as the prefab “arms.” However, just getting “legs” to spawn in is a pain, and no matter what I do I keep getting this error. I have no idea how to fix this and I’ve been trying for about 3 hours now. Here’s my code. Please help.

using UnityEngine;
using UnityEngine.Networking;
using Mirror;
public class CustomNetworkManager : NetworkManager {

    public GameObject legsPrefab;
    public GameObject armsPrefab;

    public override void OnClientConnect(NetworkConnection conn) {
        base.OnClientConnect(conn);
        Debug.Log("Player Added");
        GameObject player = (GameObject)Instantiate(legsPrefab, Vector3.zero, Quaternion.identity);
        NetworkServer.AddPlayerForConnection(conn, player);
    }
 }

@snazzy_man1
It took me 3 weeks to figure it out. This worked for me:

 public override void OnClientConnect(NetworkConnection conn)
        { 
            thisConnection = conn;
    
            // OnClientConnect by default calls AddPlayer but it should not do
            // that when we have online/offline scenes. so we need the
            // clientLoadedScene flag to prevent it.
            if (!clientLoadedScene)
            {
                // Ready/AddPlayer is usually triggered by a scene load
                // completing. if no scene was loaded, then Ready/AddPlayer it
                // here instead.
                if (!NetworkClient.ready) NetworkClient.Ready();
                {
                    NetworkClient.AddPlayer();
                }
            }
    
            base.OnClientConnect(conn);
        }

With just the code up here it should only work for host.
Then you should add this in order to spawn the client on the first scene (assuming that you have “autoCreatePlayer” set to false):

public override void OnRoomClientSceneChanged(NetworkConnection conn /*I guess that this connection is not suited to replacePlayerConnections*/) 
    {
        // You should Only call AddPlayer for normal scene changes, not additive load/unload
        if (NetworkClient.localPlayer == null)
        {
            // add player if existing one is null
            NetworkClient.AddPlayer();
        }
}

Lastly, to replace players connections, I assume you should use something like that (or whatever you need) inside “OnServerChangeScene”:

public override void OnServerSceneChanged(string newSceneName)
    {
        if (newSceneName.Contains(GameplayScene))
        {
            foreach (NetworkConnectionToClient connection in NetworkServer.connections.Values)
            {
                NetworkServer.ReplacePlayerForConnection(connection, Instantiate(playerPrefab));
            }
        }      
    }

I hope it’s not too late… ^^"
Anyway it might help somene else =]