Search Unity

Spawning different player prefabs.

Discussion in 'Multiplayer' started by rjdfhorn2006, Jan 19, 2016.

  1. rjdfhorn2006

    rjdfhorn2006

    Joined:
    Jun 14, 2010
    Posts:
    141
    I've been having trouble spawning different player prefabs in my multiplayer game. I've overriden OnServeAddPlayer on a custom NetworkManager script to pull from an array of GameObject prefabs (which have all been registered as a spawnable prefab). If I play alone as a host, it works fine - if I play with two games running, the second player to join (the client) will always spawn the same player prefab as the first player to join (the host) even if they select a different character (I have a GUI select character screen). Does anyone have any idea on how to do this properly? It seems like this should be something fairly easy.

    This is my overriden OnServerAddPlayer function:
    Code (CSharp):
    1. public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    2.     {
    3.         print("Trying to add: " + charSelect.GetPlayerPrefab().name);
    4.         GameObject player = (GameObject)Instantiate(charSelect.GetPlayerPrefab(), Vector3.zero, Quaternion.identity);
    5.         NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
    6.  
    7.     }
     
  2. KevinTriton_

    KevinTriton_

    Joined:
    Jul 7, 2012
    Posts:
    18
    I am fairly new to UNET, but here goes

    If I am correct, OnServerAddPlayer is called on the server (the host) when a client joins, and therefore, charSelect.GetPlayerPrefab() would only be the one the server selects.

    Maybe try using OnStartClient() to pass an index of the playerPrefab to a Command (only runs on server) and spawn the player prefab on the server according to that index?

    I'm am not too familiar with what all code you have and what outcome you need; maybe post more of your code in the future?

    Have' nice day
     
  3. EDevJogos

    EDevJogos

    Joined:
    Jul 24, 2014
    Posts:
    75
    I just started a test project but, i have a script quite similar to yours and it Works, maybe it's your GetPlayerPrefab() or the prefab itself that's not right. Note that OnServerAddPlayer is only called on the server, and the object instantiate later on the cliente is the prefab it self. No changes made on the prefab in the server will go to the cliente unless the variable itself is synced. Like you have only one prefab and GetPlayerPrefab() changes the Sprite of it according to the character selected, this change will only happen on the server.
     
    Last edited: Jan 21, 2016