Search Unity

Instantiating a prefab - need help :(

Discussion in 'Getting Started' started by badSkin, Nov 23, 2018.

  1. badSkin

    badSkin

    Joined:
    Jan 10, 2018
    Posts:
    6
    I have a working game but realized that instead of actually using a prefab, I've been doing everything by code (adding components via C#) and would like to simply load a prefab...

    but for the life of me I cannot figure out how to do it. All examples I've found either reference some outdated 'Resources' folder or they don't seem to reference a prefab filename.

    In my case I have a prefab (in my prefab folder) called 'Player'. It has a script component (also called Player) that has a public gameobject variable called NameObj that I've made point to another prefab called 'Name'.

    Without loading the Player prefab I can (via script) create a new game object and add the 'Player' component to it, but when I do that NameObj is null. So loading the actual prefab would be better.

    How the heck does one load a prefab?
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    The Resources folder is not outdated. And you don't load prefabs by filename.

    You have two choices: either load by name from the Resources folder, or instantiate a prefab that you already have a reference to (in a public property of type GameObject, for example). I'm pretty sure this is exactly what the manual tells you.

    So whatever code you want to load the Player prefab, give it a playerPrefab property, and drag your prefab in, then pass it to Instantiate. Or, move your prefab into the Resources folder and load it by name.
     
    fct509 likes this.
  3. badSkin

    badSkin

    Joined:
    Jan 10, 2018
    Posts:
    6
    Thank you!