09 Sept 2014Unity15 Comments

Basics of Photon Unity Networking (PUN)

In this tutorial i’m going to explain fundamentals of Unity – Photon networking. This also very similar to unity networking which i explained in previous tutorial. Photon is a real time game development framework which has many services like photon server, photon cloud and photon chat. Here we are going to use photon cloud (photon PUN). The advantage of photon cloud is, it doesn’t required a server.

In unity networking, the host will be one of connected client, so connection will dropped if client leaves, but in photon it never happen because photon uses dedicated server.

Unity Networking or Photon ?

Find out your self :)

Since photon networking (photon pun) is very similar to unity networking, i recommend you to refer unity networking tutorial first if you are a newbie ;)

Getting started.

Lets start from the sketch. Create new unity project and download photon pun unity package from asset store. Photon Unity Networking Free this is a free plugin, but if you are wish to build for the mobile platforms you will need to have unity pro license or photon PUN + plugin. For this tutorial, unity free licence and photon pun free plugin is sufficient. Once you imported the downloaded package, you need to setup. Open PUN wizard ( Window > photon unity networking ). if you already have a photon account, enter your app id into the pun wizard. If not, create new photon account by entering your email address into pun wizard. and get your app id by clicking link on received email. Finally select the nearest cloud region and save settings. Now our basic setup is complete.

Mechanism

Consider this is like a chat room, Anyone can create new room, room has unique name and maximum users. people can join existing rooms. The person who creates the room has more privileges. Photon cloud also behaves similar to this.

Photon server always uses master server and one or more game servers. Master server manages list of game servers and all the currently running games on those servers. To pick a game, all the clients connect to master server then, master server will redirect them to game servers based on their settings.

Its time to create a room. :) Create new new unity project and C # script. Re name newly added c sharp script as “NetworkManager.cs” and drag it to the camera component. Then copy the following code into it.

Create a Room

PhotonNetwork.CreateRoom()

will create a room with given room name. and also you need to set some other properties of the room like maximum players, room visibility, room open or not (open means other players can join this room). When room creation successful

PhotonNetwork.CreateRoom()

will be called.

Connect to a room

what we want to know? can join by providing room name. yep, if room is open and not exceeding maximum players we can :)

Use PhotonNetwork.JoinRoom() to join any open room. pass room name as a parameter. Edit your code as follows

Build a standalone build and test, create room and from the other instance try join to created room, You should be able to join room but this is not practical,

Just to Remember

If you are going to develop multiplayer game using PUN, should use better method to find available rooms and connect to them. Use PhotonNetwork.GetRoomList() to get the list of currently available rooms or just join to a random room by PhotonNetwork.JoinRandom()

Load Levels

Now we want to start our game once client join the room. Lets add PhotonNetwork.LoadLevel() to the OnJoinRoom(). Create new scene and name it Game,

Spawning the player

Like in Unity Networking , game objects can instantiate over network. But in photon, our prefab must available directly under the Resources folder so that the prefab can be loaded at run time.

Add a directional light to the scene. Add a new Plane (GameObject > create other > Plane) and rename it as Floor. Change its position to (0, -1.8,0)

Create a Cube (GameObject > create other > cube). this will be our player. Rename it as player. Add a rigid-body to it and don’t forget to freeze rigid-body’s rotation .Create new c # script and name it “Player.cs”. and add it to the player object. In hierarchy create a new folder called “Resources” This will be the home for any object which are going to spawn over the network. Make a prefab using our player object and save it under Resources folder. Now we want to instantiate our “Plyaer” object when Load the newly created Game Scene. Create another C# script and save it as GameView.cs and attach it to the Camera component. Add following code to the GameView.Awake()

Move the Player.

Our next step will be synchronise the player movements across the network. We need to add photon view component to the player object (Component > Miscellaneous > Photon View). This enables us to send data packages over the network.Drag the transform component of to observe field of the photon view Leaves the observe option as “Reliable delta compressed” and update the player prefab.

Reliable delta compressed means the synchronised data will send only if values of the observe fields changed.

By default all the scripts inherits from Monobehaviour, Remove monibehaviour and inherit form Photon.Monobehaviour. this enable photon networking in this class.

Add following code to the Player.cs to control the player. Like we did in unity networking, need to check the object is on the network “is mine”.

Create a built and test.up to this point you should able to control your local player and observe other clients movements. But if you watch carefully, there is a notable lag between movements. Lets try to reduce that lag.

State Synchronisation.

State Synchronisation constantly updates values over the network. This is suitable for data witch are changes regularly like player movements. Go to the photon view component of the player prefab and change its observed field by dragging player.cs script component in to the observe field. Add OnPhotonSerializeView() method to the Player.cs

OnPhotonSerializeView() ?

This method is used to customise which data a PhotonView regularly synchronises. Your code defines if something gets sent, what content gets sent and how that gets used on receiving clients. This will called every ‘network-update’ when observed by PhotonView

The user sends the rigid-body’s position with stream.SendNext() and this is received by the clients with stream.ReceiveNext().

Make another build and test yourself. The result won’t be differ than before. Lets optimise this like we did on Unity Networking tutorial.

Interpolation ?

Further optimisation . . .

Based on the network conditions there will be a small delay, for reduce that small delay we can predict our players next position based on the current velocity.

Remote procedure calls (RPC)

RPC let you to call functions on the remote machine. Invoking RPC is very easy and same as calling a normal method. By adding [RPC] in front of any function, it can be called over the network. But always keep in mind,

RPC call may have many parameters, but always try to keep those minimum in order to increase performance.

In games RPC used to execute events or share data between two parties. Lets add RPC to change level when remote player connect to the room. Go back to Menu scene and add PhotonView component(Component > Miscellaneous > Photon View) to Main Camera. and in NetworkManager.cs Change the Monobehavior to Photon.Monobehaviour like we did in our Player script. Add following RPC function to the NetworkManager.cs and call it from OnPhotonPlayerConnceted() method.

Download complete unity project

Tags: