Wednesday, December 1, 2021

Instantiate Photon object without using Resources folder

 https://forum.unity.com/threads/solved-photon-instantiating-prefabs-without-putting-them-in-a-resources-folder.293853/


PUN 2 is using a PrefabPool to get a GameObject instance. You can write your own but you can also very easily fill the existing pool of type DefaultPool.

The attached MonoBehaviour has a list of "prefabs", which can be edited in the Inspector. This reference means that the assets don't have to be in the Resources folder. In Start(), the list is used to "fill" the DefaultPool. That's enough.

Code (CSharp):
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using Photon.Pun;
  4.  
  5.  
  6. public class PreparePool : MonoBehaviour
  7. {
  8.     public List<GameObject> Prefabs;
  9.  
  10.     void Start ()
  11.     {
  12.         DefaultPool pool = PhotonNetwork.PrefabPool as DefaultPool;
  13.         if (pool != null && this.Prefabs != null)
  14.         {
  15.             foreach (GameObject prefab in this.Prefabs)
  16.             {
  17.                 pool.ResourceCache.Add(prefab.name, prefab);
  18.             }
  19.         }
  20.     }
  21. }

No comments:

Post a Comment