Search Unity

How do you load a prefab with Resources.Load

Discussion in 'Scripting' started by boylesg, Mar 25, 2016.

  1. boylesg

    boylesg

    Joined:
    Feb 18, 2016
    Posts:
    275
    It has also been asked a million times but the other examples I have seen don't seem to be of any help top me.

    Code (CSharp):
    1.     private static GameObject m_particlesMuzzleFlash = Resources.Load("MuzzleFlash") as GameObject;
    2.  
    MuzzleFlash is a prefab in the folder "PREFABS" under "Assets".

    How do I load it? "PREFABS/MuzzleFlash" does not work. Unity is telling me that m_particlesMuzzleFlash is null when I try to instantiate.
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    To use Resources.Load, the object must be in a Resources folder (there can be multiple).

    So your folder structure could look like "Assets/Resources/Prefabs/MuzzleFlash"

    Then to load it use
    Code (csharp):
    1. Resources.Load("Prefabs/MuzzleFlash") as GameObject;
     
  3. Marc7

    Marc7

    Joined:
    Mar 24, 2016
    Posts:
    9
    Hi!!

    Just put a variable:

    public GameObject muzzleFlashPrefab;

    Inside the method that you crated for the MuzzleFlash you write:

    void methodMuzzleFlash(){
    var muzzleFlashPrefab = Resources.Load("Prefabs/MuzzleFlash") as GameObject;
    var muzzleFlash = GameObject.Instantiate(muzzleFlashPrefab, transform.position, transform.rotation);
    }
     
    thewalkingprawn, canbyk and leni8ec like this.
  4. brakgta123

    brakgta123

    Joined:
    May 13, 2019
    Posts:
    1