Create prefabs on the fly

edited in Questions and Answers
Hey guys,

So I've only been using Unity for a few days and have got a bit stuck. I have a prefab with some scripts attached to it, but now I want to create this prefab from code and draw it to the screen. It doesnt come up in the code so I cant use the Instantiate method :/

Thanks,
Dom

Comments

  • There are 2 ways (that I know about) that you can do this.

    The first, and probably the quickest, is to expose a variable in the inspector and use Instantiate with this reference.
    public GameObject prefabToInstantiate;//the reference, drag and drop the prefab in here in the inspector
    
    public void Start(){
       Instantiate(prafabToInstantiate);
    }


    The second is to drop the prefab in the resources folder in the project hierarchy then use Resources.Load to instantiate it.
    public void Start(){
       Instantiate(Resources.Load("prefabName"));//there needs to be a prefab with name prefabName in the resources folder
    }


    Hope this was some help. :)
  • Awesome, thanks :) I kinda figured it out doing it the second way!
Sign In or Register to comment.