CodeBlanks Logo Icon CodeBlanks

Photon Unity Networking

Learn room and connection concepts with PUN 2.

Photon Unity Networking (PUN 2)

PUN 2 is a popular cloud-based networking solution developed for Unity. It connects clients via Photon Cloud without requiring the developer to host and manage physical servers.

using Photon.Pun;

public class NetworkLauncher : MonoBehaviourPunCallbacks {
    void Start() {
        PhotonNetwork.ConnectUsingSettings();
    }
}

Inheriting from MonoBehaviourPunCallbacks allows you to listen to connection, room creation, and player join events with ease.

Lobby and Room Structure

Upon connecting to Photon Cloud, players first arrive in a Lobby waiting area. To play a match together, players must join a common Room.

// Creating a new room
PhotonNetwork.CreateRoom("Arena_01");

// Joining an existing room
PhotonNetwork.JoinRoom("Arena_01");

Players inside the room can see and synchronize each other's avatars in real time using the PhotonView component.

Practice PUN connection status

Define a Start method. Inside, print the text "Photon Cloud baglantisi kuruldu" using Debug.Log.

Starter code

Player.cs
using UnityEngine;

public class PunConnector : MonoBehaviour
{
    // Start icinde PUN baglanti durumunu yazdir
}

Sample solution

Player.cs
using UnityEngine;

public class PunConnector : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Photon Cloud baglantisi kuruldu");
    }
}

Expected output

Photon Cloud baglantisi kuruldu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method is called in PUN 2 to connect the project to Photon Cloud servers?

  • PhotonNetwork.CreateRoom()
  • PhotonNetwork.JoinLobby()
  • PhotonNetwork.ConnectUsingSettings() Correct answer
  • PhotonNetwork.DisconnectImmediately()

Explanation: The PhotonNetwork.ConnectUsingSettings() method initiates connection to Photon Cloud using the project's AppID settings.

2 Connect to Photon server

Question
PhotonNetwork.____();
Answer
PhotonNetwork.ConnectUsingSettings();

Explanation: In the PUN 2 library, the 'ConnectUsingSettings' method is called to connect to the server.

3 PUN 2 concepts

Term Meaning
PUN Photon Unity Networking library
PhotonNetwork Static class for main networking calls
Room Shared match space where players play
Lobby Waiting hall where rooms are listed

All lessons in Advanced