Netcode Spawn Prefab

Good morning guys, I am struggling with the netcode. Let’s start with the fact that I’m a neophyte and I’ve been using it really recently, I’m faced with this scenario:
In the scene I have two classic Host and Client buttons, as well as having two other buttons referring to two creatures. The user before connecting has to select the creature he wants to use, then he clicks, the creature is set to an int 0 or 1 based on the one clicked and then he decides whether to be a host or be a client.
So far so good.

Now, I would like when a user logs in, it passes the selected creature to the server. When there are 2 creatures selected (so 2 players connected) I would like the server to send the clients the creatures to be spawned, so their own creature and the opponent’s creature. Eventually in the scene should be: on the right player creature, on the left opponent creature.

Any advice?

You can select the correct creature prefab by passing a value on connection and selecting the correct prefab hash in Connection Approval. There’s an explanation of how to do it there but here’s an abridged version:

    public class ApprovalSceneController : MonoBehaviour
    {
        [SerializeField] List<uint> playerPrefabHashes;

        void Start()
        {
            Application.targetFrameRate = 15;

            if (!ParrelSync.ClonesManager.IsClone())
            {
                NetworkManager.Singleton.ConnectionApprovalCallback += OnConnectionApproval;
                NetworkManager.Singleton.NetworkConfig.ConnectionData = BitConverter.GetBytes(0);
                NetworkManager.Singleton.StartHost();
            }
            else
            {
                NetworkManager.Singleton.NetworkConfig.ConnectionData = BitConverter.GetBytes(1);
                NetworkManager.Singleton.StartClient();
            }
        }

        private void OnConnectionApproval(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
        {
            Debug.Log("OnConnectionApproval playerPrefabHashes: " + playerPrefabHashes.Count);

            if (request.Payload.Length > 0)
            {
                int playerPrefabIndex = BitConverter.ToInt32(request.Payload, 0);

                Debug.Log($"OnConnectionApproval playerPrefabIndex: {playerPrefabIndex} hash: {playerPrefabHashes[playerPrefabIndex]}");

                response.PlayerPrefabHash = playerPrefabHashes[playerPrefabIndex];
                response.CreatePlayerObject = true;
                response.Approved = true;
            }
            else
            {
                response.Approved = false;
            }
        }
    }

Thank you very much for your reply!
Isn’t it a bit complicated as a solution? Maybe I didn’t explain it well myself… I was thinking more something like when the player spawns a serverrpc call is made that passes its id and the creature’s id. The server adds the player to the dictionary. When the server adds the second player with an if count check on the dictionary it sends clientrpc calls to the two clients with the contents of the dictionary (two calls then). The clientrpc functiond checks if the id is different from the local player and sets the enemy of the other client’s id in a local manager.

I thought it was the simplest solution :slight_smile: as long as players are allowed to select the same creature, if not you’d need the selection to happen after connection.

What you’re suggesting is a different approach which is fine. You can send the creature id in an rpc and have it stored on a network variable on the player, that way host and client will receive the value without having to worry about more rpcs. It does depend though if they’re allowed to be the same creature or not.

Yes they’re allowed to be the same creature. I’m trying to the rpc method but i’m facing some issues.

This is the Player prefab that is spawned.

public class PlayerManager : NetworkBehaviour
{

    [SerializeField]
    public GameObject creaturePrefab;
  
    public static PlayerManager LocalInstance { get; private set; }
 
    public int Selected;
    public int Enemy;
    public override void OnNetworkSpawn()
    {
        base.OnNetworkSpawn();
        if (IsOwner)
        {
            LocalInstance = this;
            gameObject.name = "Player";
            int selected = SceneInitializer.Instance.selectedCreature;
         
            PlayersInfo.Instance.AddPlayerInfoServerRpc(selected, new ServerRpcParams());
        }
        else
        {
            gameObject.name = "Enemy";
        }
    }

}

Selected is the creature I have selected before, Enemy is the creature selected by the enemy of course.

This is the script in a GameObject called PlayersInfo

public class PlayersInfo : NetworkBehaviour
{
    public static PlayersInfo Instance;
    public event EventHandler OnPlayerAdded;
    public event EventHandler OnPlayersReady;

    private Dictionary<ulong, int> Players;

    private void Awake()
    {
        Instance = this;

        Players = new Dictionary<ulong, int>();
    }

    [ServerRpc]
    public void AddPlayerInfoServerRpc(int i, ServerRpcParams serverRpcParams)
    {
        Debug.Log("CALLED");
      
        if (!IsServer) return;
      
        if(!Players.ContainsKey(serverRpcParams.Receive.SenderClientId))
        {
            Players.Add(serverRpcParams.Receive.SenderClientId, i);
            OnPlayerAdded?.Invoke(this, EventArgs.Empty);
            Debug.Log("Added " + serverRpcParams.Receive.SenderClientId);
        }
      
        if(Players.Count == 2)
        {
            foreach(var p in Players)
            {
                SetClientRpc(p.Key, p.Value);
            }
        }
      
    }
    [ClientRpc]
    public void SetClientRpc(ulong id, int creature)
    {
        Debug.Log(OwnerClientId);

        OnPlayersReady?.Invoke(this, EventArgs.Empty);
    }

    public void PrintDictionary()
    {
        foreach (KeyValuePair<ulong, int> entry in Players)
        {
            Debug.Log("Client ID: " + entry.Key + ", Creature: " + entry.Value);
        }
    }
}

The problem is that the ServerRpc AddPlayerInfoServerRpc is never called… Do yuou know why?

EDIT: The clientRpc call is only to know if it’s working

You could try moving the code from OnNetworkSpawn to Start, I can’t remember if the object is fully initialised at that point, IsOwner might not be set. Best tip I can give you is log EVERYTHING. :smile:

Yeah it is initialized because the gameobject name is set to Player!

The name isn’t a network related value, IsOwner will be false initially. If that’s not the issue check the object in the editor and make sure the NetworkObject component has a NetworkObjectId and the flag values look correct, as well as the observers. If it has a NetworkObjectId I can only think the rpc is called too early. Put a log in the rpc to know when it’s called.

The Log is already in the RPC (“Called”) and is never trigger. I’ve just tried to connect an host and then a client, when i connect the client i’ve an error on it

Only the owner can invoke a ServerRpc that requires ownership!

For AddPlayerInfoServerRpc? It sounds like PlayersInfo is owned by the host and only the owner can make the rpc calls. You can get around this changing the annotation to [ServerRpc(RequireOwnership = false)] for now but you might want to re-work your code later on.