Version: 2017.2
Converting a single-player game to Unity Multiplayer
Network Clients (clientes de red) y Servers (servidores)

Multiplayer Lobby

Many multiplayer games have a staging area (often known as a “lobby”) for players to join before playing the actual game. In this area, players can pick options and set themselves as ready for the game to start.

The NetworkLobbyManager is a specialized NetworkManager that provides a lobby for Unity Multiplayer games. Its functionality includes the following:

  • Limits the number of players that can join
  • Supports multiple players per client, with a limit on the number of players per client
  • Prevents players from joining game in-progress
  • Has a per-player ready state, so that the game starts when all players are ready
  • Has per-player configuration data
  • Allows re-joining the lobby when the game is finished
  • Funciones virtuales que permiten una lógica personalizada para eventos de lobby
  • Una interfaz de usuario simple para interactuar con el lobby

Abajo hay unas funciones virtuales NetworkLobbyManager llamadas en el servidor:

All of the above server functions have empty default implementations, except for OnLobbyServerPlayersReady, which calls ServerChangeScene with the PlayScene.

Abajo están las funciones virtuales NetworkLobbyManager llamada en el cliente:

Todas las funciones cliente de arriba tienen una implementación vacía predeterminada.

Lobby player objects

There are two kinds of player objects, each of which has a Prefab slot in the NetworkLobbyManager. The slots can be seen in this screenshot:

El LobbyPlayer es creado del LobbyPlayerPrefab cuando un jugador se une al lobby:

  • Un LobbyPlayer para cada jugador
  • Creado cuando el cliente se conecta, o un jugador se agrega
  • Existe hasta que el cliente se desconecta
  • Mantiene la flag ready ("lista) para este jugador para el lobby
  • Maneja comandos mientras se está en el lobby
  • Agrega scripts de usuario a este prefab para mantener datos del jugador específicos al juego
  • Este prefab debe tener un componente NetworkLobbyPlayer

Minimum Players

The Minimum Players field represents the minimum number of “Ready” players in the Lobby to start the Match with. If the number of connected clients is more than the “Minimum Players” value, then waiting for all connected clients to become “Ready” starts the Match.

Por ejemplo si “Minimum Players” es configurado a 2:

  • Start one instance of the game and start Host. Then in game Lobby UI press Start for your player. You are still in Lobby mode, because the minimum number of Ready players to start the game is 2.
  • Start two more instances of the game, and start Clients there. It doesn’t matter that “Minimum Players” set to 2. Wait for all connected players to become Ready.
  • Press Start in Lobby UI for one player. Two players are Ready, but still in Lobby mode. Press “Start” in the Lobby UI for the last player, and all players are moved to Game mode.

GamePlayer

El GamePlayer es creado del GamePlayerPrefab cuando el juego empieza:

  • Un GamePlayer para cada jugador
  • Created when game Scene is started
  • Se destruye cuando se re-ingresa al lobby
  • Maneja comandos mientras se está en el juego
  • This Prefab must have a NetworkIdentity component

El componente NetworkLobbyPlayer es utilizado para objetos LobbyPlayer. Este proporciona algunos callbacks de funciones virtuales que pueden ser utilizados para un comportamiento de lobby personalizado

    public virtual void OnClientEnterLobby();
    public virtual void OnClientExitLobby();
    public virtual void OnClientReady(bool readyState);

The function OnClientEnterLobby is called on the client when the game enters the lobby. This happens when the lobby Scene starts for the first time, and also when returning to the lobby from the gameplay Scene.

The function OnClientExitLobby is called on the client when the game exits the lobby. This happens when switching to the gameplay Scene.

La función OnClientReady se llama en el cliente cuando el estado ready del jugador cambia.

Adding the lobby to a game

Proceso de agregar un NetworkLobby a un juego multi-jugador (sin utilizar el paquete de asset multiplayer-lobby):

  • Create a new lobby Scene
  • Add the Scene to the Build Settings (menu: File > Build Settings…), as the first Scene
  • Create a new GameObject in the new Scene (menu: GameObject > Create Empty), and name it LobbyManager
  • Add the NetworkLobbyManager component to the LobbyManager GameObject
  • Add the NetworkManagerHUD component to the LobbyManager GameObject
  • In the Inspector window for the NetworkLobbyManager component, set the Lobby Scene slot of the NetworkLobbyManger to the Scene that contains the LobbyManager GameObject
  • Set the Play Scene slot of the NetworkLobbyManager to the main gameplay Scene for the game
  • Create a new GameObject and name it LobbyPlayer
  • Add the NetworkLobbyPlayer component to the LobbyPlayer
  • Create a Prefab for the LobbyPlayer (drag it into the Project window), and delete the instance from the Scene
  • On the LobbyManager’s NetworkLobbymanager component, assign the LobbyPlayer prefab to the Lobby Player Prefab slot
  • Assign the Prefab for the player in the main game to the Game Player Prefab slot
  • Save the Scene
  • Ejecute el juego

This version of the NetworkLobbyManager uses the OnGUI user interface like the NetworkManagerHUD. For a better user interface, use the multiplayer-lobby Asset package (found in the NetworkStarter sample package, on the Unity forums).

The NetworkLobbyManager has many virtual function callbacks that can be used for custom lobby behaviour. The most important is OnLobbyServerSceneLoadedForPlayer, which is called on the server for each player as they transition from the lobby to the main game. This is the ideal place to apply settings from the lobby to the player object.

    // for users to apply settings from their lobby player object to their in-game player object
    
    public override bool OnLobbyServerSceneLoadedForPlayer(GameObject lobbyPlayer, GameObject gamePlayer)
    {
        var cc = lobbyPlayer.GetComponent<ColorControl>();
        var player = gamePlayer.GetComponent<Player>();
        player.myColor = cc.myColor;
        return true;
    }

Sample project

Hay un proyecto ejemplo en el Unity asset store que utiliza el NetworkLobbyManager y proporciona un GUI para el lobby. Este puede ser utilizada como punto inicial para crear un jugador multi-jugador con un lobby.

Proyecto ejemplo de Lobby

Converting a single-player game to Unity Multiplayer
Network Clients (clientes de red) y Servers (servidores)
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961