Setting Up Photon

1. Install photon

Search for Photon Unity Networking in the Unity Asset Store, then download and import it into your project. (Note whether you are downloading PUN1 or PUN2. This tutorial uses PUN2, as there may be some compatibility issues with PUN1. It is recommended to use PUN2).

Pay attention to resolving issues related to assemblies.

  • Open the assembly of NRSDK.

  • Find the "Assembly Definition References" section and click the "+" button to add a new reference. In the new reference, select the Photon assembly PhotonUnityNetworking and PhotonRealtime. Click the "Apply" button to save your changes.

2. Set up Photon in Unity

  1. Register and create a new application on the official website of Photon, then obtain the App ID for your application.

  1. In Unity, open PhotonServerSettings (Window > Photon Unity Networking), and then enter your App ID.

3. Joining a room

A crucial prerequisite for sharing an anchor among different users is that they are in the same room. Therefore, we need to set up a script to allow them to join the same room.

The joinedRoomIndicator is used to indicate a successful room joining. The method used here is to change the color of the join button after successfully joining.

using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;

public class JoinRoomButton : MonoBehaviourPunCallbacks
{
    public Button joinedRoomIndicator;

    public void OnButtonClick()
    {
        // Connect to the Photon master server
        if (!PhotonNetwork.IsConnected)
        {
            PhotonNetwork.ConnectUsingSettings();
        }
        else
        {
            TryJoinRoom();
        }
    }

    public override void OnConnectedToMaster()
    {
        Debug.Log("Connected to Photon master server");
        TryJoinRoom();
    }

    private void TryJoinRoom()
    {
        // Try to join the room "MyRoom"
        PhotonNetwork.JoinRoom("MyRoom");
    }

    public override void OnJoinedRoom()
    {
        Debug.Log("Joined room: " + PhotonNetwork.CurrentRoom.Name);
        
        joinedRoomIndicator.image.color = Color.green;
    }

    public override void OnJoinRoomFailed(short returnCode, string message)
    {
        Debug.Log("Failed to join room");
        // If we failed to join the room, it might not exist, so let's try to create it
        PhotonNetwork.CreateRoom("MyRoom");
    }

    public override void OnCreatedRoom()
    {
        Debug.Log("Created room: " + PhotonNetwork.CurrentRoom.Name);
    }

    public override void OnCreateRoomFailed(short returnCode, string message)
    {
        Debug.Log("Failed to create room");
    }
}

Last updated