Back to Writing
NOTESunityphotonpun2addressablesnetworking

PUN2 (Photon Engine) - Using Addressables with PhotonNetwork.Instantiate

October 9, 2020Updated Feb 17, 2026

![](

Y1Wg0Q8AIqBe8NzVlsg.A8ld8egcNKez5EAqn2HqV78SrA5pPvf2c0PljEKb5gQg.PNG.cdw0424/image.png?type=w966)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.AddressableAssets;
using System.Threading.Tasks;

public class Matchmaker : MonoBehaviourPunCallbacks
{
public AssetReference photonObject;

List<GameObject> gameObjects;

async void Start()
{
gameObjects = new List<GameObject>();

DefaultPool defaultPool = PhotonNetwork.PrefabPool as DefaultPool;

Task<GameObject> task = photonObject.LoadAssetAsync<GameObject>().Task;

await task;

gameObjects.Add(task.Result);

defaultPool.ResourceCache.Add(gameObjects[0].name, gameObjects[0]);
Debug.Log("Object added to cache.");

Debug.Log("Start");
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.GameVersion = "0.1";
}

private void OnDestroy()
{
photonObject.ReleaseAsset();
}

public override void OnConnectedToMaster()
{
Debug.Log("OnConnectedToMaster() was called by PUN.");

PhotonNetwork.JoinRandomRoom();
}

public override void OnJoinedRoom()
{
Debug.Log("OnJoinedRoom() called by PUN. This client is now in a room.");

float randomX = Random.Range(-6f, 6f);

PhotonNetwork.Instantiate(
gameObjects[0].name,
new Vector3(randomX, 0f, 0f),
Quaternion.identity,
0
);
}

public override void OnJoinRandomFailed(short returnCode, string message)
{
Debug.Log("OnJoinRandomFailed() was called by PUN. No random room available, so we create one.\nCalling: PhotonNetwork.CreateRoom");

// #Critical: Failed to join a random room. The room may not exist or may be full. No worries, we create a new room.
PhotonNetwork.CreateRoom(null);

//PhotonNetwork.CreateRoom(null, new RoomOptions{MaxPlayers = 4});
}
}

Verified that it works correctly.