Search Unity

[SOLVED] Photon: Instantiating prefabs without putting them in a "Resources" folder?

Discussion in 'Connected Games' started by Deleted User, Jan 27, 2015.

  1. Deleted User

    Deleted User

    Guest

    How can I PhotonNetwork.Instantiate prefabs that are not located in the root of the "Resources" folder?
     
  2. flaminghairball

    flaminghairball

    Joined:
    Jun 12, 2008
    Posts:
    866
    If your folder structure looks like so:

    Assets
    - Resources
    - - Player.prefab

    You instantiate it with:
    PhotonNetwork.Instantiate("Player");

    You can also make your folder structure like this:
    Assets
    - Actors
    - - Player Controlled
    - - - Resources
    - - - - Player.prefab <--- Will still load with the above code, as it's still top-level resources

    Or, you can do this:
    Assets
    - Resources
    - - Actors
    - - - PlayerControlled
    - - - - Player.prefab

    And load it like so:

    PhotonNetwork.Instantiate("Actors/PlayerControlled/Player")
    The forward slashes act as telling Unity to navigate the folder hierarchy inside a resources folder. Note that you can also have multiple resources folders if you so desire.
     
    Deleted User likes this.
  3. Deleted User

    Deleted User

    Guest

    What if I don't want to have a Resources folder at all?
     
  4. flaminghairball

    flaminghairball

    Joined:
    Jun 12, 2008
    Posts:
    866
  5. Hr-Orange

    Hr-Orange

    Joined:
    Aug 25, 2018
    Posts:
    1
    does anybody have a link that still works or an example of how to spawn without having the resources folder at all?
     
  6. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    2,187
    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. }