How to spawn a different prefab with Mirror in Unity?

8.1k views Asked by At

I am trying to create a LAN game for my school thesis and I can't seem to figure out how to spawn different prefabs for each player that connects to the server using Mirror in Unity. I am able to create a room but every time a player joins, he will have the same prefab as the server and I want it to be different.

This is the settings of my Network Manager. I attached a script to it called Char1 with a code from here

I am able to create a room and sync everything with Parrelsync but unable to set different prefabs for each player that will connect. Any info that you need in order to help me just tell me and i will try to answer asap.

1

There are 1 answers

1
Nathanael Gass On

Since the answer wasn't given to your question:

At the top of your custom NetworkingManager class (which should inherit from NetworkManager, by the way), you should create a public GameObject variable. When your code compiles it will show in your editor as whatever you named it. After that, you can set it to a prefab object that you've made.

After that, it's just a matter of setting the GameObject you're instantiating to that in the code.

public class MyNetworkingManager : NetworkManager
{

public GameObject PlayerPrefab2;


public override void OnStartServer()
{
    base.OnStartServer();
    NetworkServer.RegisterHandler<CharacterCreatorMessage>(OnCreateCharacter);
}

public override void OnClientConnect(NetworkConnection conn)
{
    base.OnClientConnect(conn);

    //send the message here
    //the message should be defined above this class in a NetworkMessage
    CharacterCreatorMessage characterMessage = new CharacterCreatorMessage
    {
        //Character info here
    };

    conn.Send(characterMessage);

}

void OnCreateCharacter(NetworkConnection conn, CharacterCreatorMessage message)
{

    if (message.character.Equals("player2"))
    {
        GameObject gameobject = Instantiate(PlayerPrefab2);
        Player2 player = gameobject.GetComponent<Player2>();
        NetworkServer.AddPlayerForConnection(conn, gameobject);
    } else if (message.character.Equals("player1"))
    {
        GameObject gameobject = Instantiate(playerPrefab);
        Player player = gameobject.GetComponent<Player>();
        NetworkServer.AddPlayerForConnection(conn, gameobject);
    }



}


}

https://mirror-networking.gitbook.io/docs/guides/gameobjects/custom-character-spawning is a good reference for the base class concepts here.