Introduction to Multiplayer Games With Unity and Photon

Learn how to make your own multiplayer game with Unity and the Photon Unity Networking (PUN) library. By Gur Raunaq Singh.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 2 of 4 of this article. Click here to view the first page.

Creating the Lobby

Here’s an overview of what the Launcher.cs script is going to do, in order:

  1. Connect to the Photon Network.
  2. Once connected, take two inputs from the user: The Player Name they want to use, and the Room Name they want to Create or Join.
  3. If a Room with the entered name doesn’t exist, create a Room with that name and make the current player the Lobby Leader. If the Room exists, the player will join the Room.
  4. Once both players have connected to the same room, the Lobby Leader can load the MainArena scene.

Open the Launcher.cs script in Assets / RW / Scripts.

Add the following lines of code in Launcher.cs after the comment // Start Method.

Don’t worry about the intermediate errors while adding the code. All the necessary code will be explained in sections below.

// Start Method
void Start() 
{
    //1
    PlayerPrefs.DeleteAll(); 

    Debug.Log("Connecting to Photon Network");

    //2
    roomJoinUI.SetActive(false);
    buttonLoadArena.SetActive(false);

    //3
    ConnectToPhoton();
}

void Awake()
{
    //4 
    PhotonNetwork.AutomaticallySyncScene = true;
}

Here’s a brief explanation of the code.

  1. When connecting to a server, PUN pings all available servers and stores the IP address of the server with the lowest ping as a PlayerPrefs key-value pair. This can lead to unexpected behavior during the connection stage. To avoid any anomalies, DeleteAll is called when the Launcher scene starts.
  2. The UI elements are hidden by default, and are activated once a connection to a Photon server is established.
  3. ConnectToPhoton is called to connect to the Photon network.
  4. The value of AutomaticallySyncScene is set to true. This is used to sync the scene across all the connected players in a room.

Loading the MainArena Scene

To get the Input from the TextField UI elements, you need a public method to store the value in a TextField. Add the following code after the comment // Helper Methods:

// Helper Methods
public void SetPlayerName(string name)
{
    playerName = name;
}

public void SetRoomName(string name)
{
    roomName = name;
}

Next, add the following methods after the comment // Tutorial Methods:

// Tutorial Methods
void ConnectToPhoton()
{
    connectionStatus.text = "Connecting...";
    PhotonNetwork.GameVersion = gameVersion; //1
    PhotonNetwork.ConnectUsingSettings(); //2
}

How this code works:

  1. The GameVersion parameter is set. This is the version string for your build and can be used to separate incompatible clients. For this tutorial, it will be set to 1 (set when the gameVersion field is declared).
  2. ConnectUsingSettings is called, which is used to connect to Photon as configured in the editor. You can read more in the docs.

Next, add the following lines of code:


public void JoinRoom()
{
    if (PhotonNetwork.IsConnected)
    {
        PhotonNetwork.LocalPlayer.NickName = playerName; //1
        Debug.Log("PhotonNetwork.IsConnected! | Trying to Create/Join Room " + 
            roomNameField.text);
        RoomOptions roomOptions = new RoomOptions(); //2
        TypedLobby typedLobby = new TypedLobby(roomName, LobbyType.Default); //3
        PhotonNetwork.JoinOrCreateRoom(roomName, roomOptions, typedLobby); //4
    }
}

public void LoadArena()
{
    // 5
    if (PhotonNetwork.CurrentRoom.PlayerCount > 1)
    {
        PhotonNetwork.LoadLevel("MainArena");
    }
    else
    {
        playerStatus.text = "Minimum 2 Players required to Load Arena!";
    }
}

Looking at each line of code comment-by-comment:

  1. The NickName parameter of the LocalPlayer is set from the private variable playerName. This is the name that will be available to everyone you play with on the Photon network, and is used as a unique identifier.
  2. An object of class RoomOptions is declared. This wraps up common room properties required when you create a room. It can be used to give the user control of various characteristics of the room such as maximum number of players that can join, PlayerTtl (Player Time To Live), etc. (Docs)
  3. An object of class TypedLobby is declared. This refers to a specific lobby type on the Photon server. The name and lobby type are used as an unique identifier. The Room name is set from the private variable roomName and the Lobby type is set as Default. (Docs)
  4. Finally, the JoinOrCreateRoom method of PhotonNetwork class is called with arguments — roomName, roomOptions and typedLobby that were set earlier. If the method is called by a new user with a new Room name that does not yet exist, a room is created and the user is set as the Lobby Leader. Otherwise, the other players just join the room.
  5. Once the Lobby Leader has created and joined a Room, the LoadArena button will be set active. A check is set before loading the Arena to make sure the MainArena scene is loaded only if both players have joined the room.

PUN Callback Methods

Now that you’ve added the basic building blocks of Joining and Creating a Room, all that’s left to do is add PUN Callback methods that will take care of the exception handling.

Add the following code after the comment // Photon Methods:

// Photon Methods
public override void OnConnected()
{
    // 1
    base.OnConnected();
    // 2
    connectionStatus.text = "Connected to Photon!";
    connectionStatus.color = Color.green;
    roomJoinUI.SetActive(true);
    buttonLoadArena.SetActive(false);
}

public override void OnDisconnected(DisconnectCause cause)
{
    // 3
    isConnecting = false;
    controlPanel.SetActive(true);
    Debug.LogError("Disconnected. Please check your Internet connection.");
}

public override void OnJoinedRoom()
{
    // 4
    if (PhotonNetwork.IsMasterClient)
    {
        buttonLoadArena.SetActive(true);
        buttonJoinRoom.SetActive(false);
        playerStatus.text = "You are Lobby Leader";
    }
    else
    {
        playerStatus.text = "Connected to Lobby";
    }
}

Let’s look at what each piece of code does:

  1. As the name suggests, OnConnected gets invoked when the user connects to the Photon Network. Here, the method calls the base method onConnected(). Any additional code that needs to be executed is written following this method call.
  2. These methods provide feedback to the user. When the user successfully connects to the Photon Network, the UI Text connectionStatus is set, and the roomJoinUI GameObject is set to visible.
  3. OnDisconnected gets called if the user gets Disconnected from the Photon Network. In this case, the controlPanel GameObject is set to false, and an Error type message is logged to Unity.
  4. Finally, OnJoinedRoom is called when the user joins a room. Here, it checks if the user is the Master Client (the first user to join the room). If so, the user is set as the lobby leader and is shown a message to indicate this. The lobby leader has the power to load the MainArena scene, which is a common way of creating a room in most popular multiplayer games. Otherwise, if the user is not first to join the room, a message is shown to tell that user that they’ve successfully joined the room.

Save the Launcher.cs script and head back to the Launcher scene, and click Play.

As you can see, when the Scene starts, ConnectToPhoton gets called and the Connection status UI Text shows “Connecting…”. Once successfully connected, the text changes to “Connected”, and the visibility of the roomJoinUI GameObject is set to true.

Next, the user can enter their Name and the name of the Room that they want to Create or Join by clicking on the Join Room button.

Finally, if the user is the Master Client, the playerStatus Text is set to “You are now the Lobby Leader!” and the Load Arena button is set active. Otherwise, an indication of a successful lobby join is shown.

At this point you can test joining a Room by building an executable of the project for your Operating System by selecting File ▸ Build and Run. You should be able to load the MainArena scene using both your newly built executable and the Unity Editor joined to the same room.

However, you can see only an empty arena with no players. In the next section, you’ll learn how to add player and ball prefabs to the scene for each individual client. You’ll also sync their Position, Rotation and more across the Photon Network.