Photon Lobby and Rooms

Camilo Diaz - March 2023 

How to create lobby and rooms using Photo + Unity 

Photon Engine give us free the hosting and some API calls to synchronize our avatar's transformations across the net. It could be case were you have a large number of users in the same simulation, and you want to split them in smaller groups where they can enjoy different activities within the same VR space. Let's learn how to create rooms using Photon. 

This tutorial assumes you already know how to import Unity XR tool kits and Photon Engine in your project. If you dont, please follow this tutorial and come back when you have your Photon environment configured.



4.  Create an empty game object and rename it NetworkManager. Add a new script component to it and called it NetworkManager

5. Open the NetworkManager Script in your code editor and copy paste the following code.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using Photon.Pun;

using Photon.Realtime;

using TMPro;


public class NetworkManager : MonoBehaviourPunCallbacks

{



    private bool isConnected = false;

    public void ConnectedToServer()

    {

        if (!isConnected)

        {

            PhotonNetwork.ConnectUsingSettings(); // This code connects to the Photon server once the Unity scene starts

        }

        

    }


    public override void OnConnectedToMaster()

    {

        base.OnConnectedToMaster();

        isConnected = true;

        

    }


    public override void OnJoinedLobby()

    {

        

        // This callback happens when players joinig the general lobby

    }


    public void InitializeRoom(int room)

    {

        RoomOptions roomOptions = new RoomOptions();

        roomOptions.MaxPlayers = 4;

        roomOptions.IsVisible = true;

        roomOptions.IsOpen = true;


        string roomName = "CS1951t_"+room.ToString(); // The name of the room depends on the button label

        PhotonNetwork.JoinOrCreateRoom(roomName, roomOptions, TypedLobby.Default);

    }


    public override void OnJoinedRoom()

    {

        base.OnJoinedRoom();

        PhotonNetwork.LoadLevel(level_to_load); // Here you load you level

    }


    public override void OnPlayerEnteredRoom(Player newPlayer)

    {

        base.OnPlayerEnteredRoom(newPlayer);

    }

}

6.  Add the function InitializeRoom to the Onclick event of the UI Buttons

7 . Using your VR controllers ( with the XR interaction toolkit )  you can click any button to be send to the specified room. The users can only interact with the the ones in the same room