Getting Started with Unity Multiplayer using Photon PUN: A Beginner’s Guide

Prasanth
7 min readSep 30, 2023

--

If you’re a budding game developer taking your first steps into the exciting world of multiplayer game development with Unity, you’ve come to the right place. My aim is simple: to provide beginners with a friendly and accessible introduction to Unity multiplayer using Photon PUN (Photon Unity Networking). Whether you’re a solo developer dreaming of creating your own online game or a student exploring the fascinating realm of networked gameplay, this tutorial will guide you through the basics, step by step.

In this blog, you will learn:

  • How to set up Photon PUN in your Unity project.
  • Creating a simple multiplayer room where players can connect.
  • Create player with custom properties
  • Implementing player movement and interaction in a multiplayer environment.

To help you along this journey, I’ve prepared a GitHub repository with all the code and assets you’ll need. You can access it here

Let’s get started!

Set up Photon PUN in your Unity project

What is Photon PUN?

Photon PUN (Photon Unity Networking) is a popular and powerful networking solution for developing multiplayer games in Unity. It is part of the Photon networking ecosystem provided by Exit Games.

Create a new app in Photon

Step 01: If you don’t have a photon account, create your Photon account here.

Step 02: Create a new app. Make sure, you are selecting the Application type as Multiplayer Game and Photon SDK as PUN. Then give a name and description to your project and create.

Step 03: You can find your project under Applications -> Public Cloud. There get copy of your App ID.

Import Photon inside the Unity project

Step 01: Search for Photon PUN — 2 Free and import it into your Unity project.

Step 02: After the successful import, you will get a message box to enter the App ID or if you missed it, you can find the place to enter the App ID as shown in the below image.

Paste your App ID inside App id PUN

Now we successfully integrated the Photon PUN in our Unity project.

Creating a simple multiplayer room where players can connect

First let’s learn some essential keywords to work with Photon PUN for Unity multiplayer development.

Lobby

A virtual waiting area in multiplayer games where players gather before joining a game.

Room

A room is a virtual game instance where players interact and play together.

MonoBehaviourPunCallbacks

A class provided by Photon PUN that you can inherit from in your Unity scripts. It provides a set of callback methods that are automatically invoked by the Photon PUN framework at various points during networked gameplay.

CustomProperties

User-defined key-value pairs associated with players, rooms, or game objects. They allow you to attach custom data to these entities.

PhotonView

A component that is used to synchronize Game Objects across the network.

Photon Transform View Classic:

A component in Photon PUN that specifically deals with the synchronization of a Game Object's transform (position, rotation, and scale) across the network.

Resources folder

A special folder in Unity where you can place assets (e.g., prefabs, textures, audio files) that you want to load at runtime.

Before entering into details, create a UI screen for your lobby.

Step 01: Create a Server script & inherits the MonoBehaviourPunCallbacks class.

public class Server : MonoBehaviourPunCallbacks{

}

Step 02: Import the following libraries inside your Server script.

using ExitGames.Client.Photon;
using Photon.Pun;
using Photon.Realtime;
using System.Collections.Generic;
using UnityEngine;

Step 03: Establish a connection between your Unity application and the Photon Server. Call the following line inside the Awake / Start function of the Server script.

PhotonNetwork.ConnectUsingSettings();

Step 04: Override the following callback function that is automatically called when your Unity client successfully connects to the Photon Master Server.

public override void OnConnectedToMaster()
{
PhotonNetwork.JoinLobby();
}

This is the place where you should allow your multiplayer game client to join a lobby.

Step 05: Now Override the following callback function that is automatically called when the Unity client successfully joined in the lobby.

public override void OnJoinedLobby()
{
GameManager.Instance.ShowLobby();
}

Here you can show the lobby screen you designed hence the client successfully joined in the lobby.

Step 06: Create and call the following function when the player tries to create a room.

public void CreateRoom(string roomID)
{
//Optional
//Set your room properties if need
RoomOptions roomOptions = new RoomOptions() {
MaxPlayers = 2
};

PhotonNetwork.CreateRoom(roomID, roomOptions);
}

We can create room options (optional) based on our requirement and can pass the room id (Given by the player) and room options (if exists), inside the CreateRoom function. Which will end up with a new room with the ID we provided.

Step 07: Similarly create another function to join the room as below,

public void JoinRoom(string roomID)
{
PhotonNetwork.JoinRoom(roomID);
}

Here we need to pass the exact same room id given by the player which is used to create the room.

Step 08: Override the following callback function that is automatically called when the Unity client successfully joined in the room.

public override void OnJoinedRoom()
{
GameManager.Instance.OnJoinedRoom();
}

Finally, you can Initialize your game inside this callback function and start your game play.

Create player with custom properties

Spawn player

Step 01: Create a prefab of your player and keep it inside the Resources folder.

Multiplayer games require that player objects be synchronized across the network. When a new player joins the game, you can instantiate the player prefab and use Photon PUN to ensure that this player object is synchronized across all connected clients. Placing the prefab in the Resources folder makes it easy to load and instantiate the same prefab on all clients.

Step 02: Create a script called MyPlayer (Give any appropriate name) and attach the script to the player object.

Step 03: We have to attach a couple of components of Photon PUN called PhotonView and Photon Transform View Classic to the player as well.

Step 04: Create another script named SpawnPlayer (Give any appropriate name) and using the script, spawn your player when the game starts with the use of the Player prefab.

PhotonNetwork.Instantiate(player_name, player_position, player_rotation);

Here, you have to pass your player name (Prefab name), the position where the player should spawn and the initial rotation of the player.

Similarly, we can create and synchronize player characters, objects, or other elements that need to be shared among all players in the game using the above method provided by Photon PUN.

Set custom player properties

Set your player nickname and custom properties when a player joins the room.

Step 01: Set a nickname to your player (If required) as below,

PhotonNetwork.NickName = nick_name;

Step 02: Call the following function and Set all the required player properties as you need.

public void SetCustomProperties(Dictionary<string, string> dataDictionary)
{
Hashtable customProperties = new Hashtable();

//Add properties as you need
foreach (KeyValuePair<string, string> pair in dataDictionary)
{
customProperties[pair.Key] = pair.Value;
}

PhotonNetwork.LocalPlayer.SetCustomProperties(customProperties);
}

Note: Here I used to create a dictionary of properties and passed inside the function. You can handle as you need.

Example:

Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("score", "0");

Step 03: Let’s create few more functions for,

  • update custom property
public void UpdateCustomProperty(string key, string value)
{
Hashtable customProperties = new Hashtable();
customProperties[key] = value;

PhotonNetwork.LocalPlayer.SetCustomProperties(customProperties);
}
  • get custom property
public string GetCustomProperty(string key)
{
return PhotonNetwork.LocalPlayer.CustomProperties[key].ToString();
}
  • OnPlayerPropertiesUpdate

A callback method in Photon PUN that is automatically called when custom player properties for a player in a room are updated.

public override void OnPlayerPropertiesUpdate(Player targetPlayer, Hashtable changedProps)
{
//Each player in a room is assigned a different ActorNumber.
//This ensures that no any players within the same room share the same identifier.
//The first player to join typically gets an ActorNumber of 1, the second player gets 2, and so on.

if (changedProps["score"] != null)
{
GameManager.Instance.UpdatePlayerScoreUI(targetPlayer.ActorNumber, changedProps["score"].ToString());
}
}

Here you can execute whatever UI changes that you need to showcase with the progress of the game across the players.

Example: Update player score

Implementing player movement and interaction in a multiplayer environment

We have to make sure that everyone in the room has the access to control their own player instead of other players.

PhotonView.IsMine is a property in Photon PUN that is used to determine if the current client (player) "owns" or controls a particular GameObject with a PhotonView component, and IsMine helps identify whether the GameObject is under the control of the local player or another player.

Keep all your player movement and other controls related to player inside IsMine.

if (photonView.IsMine)
{
//Player controls and mechanisms
}

Output

Congratulations, you’ve embarked on a journey into the world of Unity multiplayer game development with Photon PUN. We’ve covered the essentials, from setting up your project and understanding the lobby system to dynamically spawning player prefabs and synchronizing game data across the network.

Happy coding!!!

--

--

Prasanth
Prasanth

Written by Prasanth

Senior Software Engineer | Game Developer

Responses (1)