Loading PreFab from c# in Unity

17,808

Solution 1

When objects are Instantiated they become GameObjects. Your code should look like this:

GameObject myItem = Instantiate(Resources.Load("myPrefab")) as GameObject;

If you want a Transform you can simply use the fact that all GameObjects have a transform component.

Transform t = myItem.transform.

Or if you really want to be a badass, you can do it all in one line:

Transform myItem = (Instantiate(Resources.Load("myPrefab")) as GameObject).transform;

Solution 2

The prefab should be put into a GameObject instead of a Transform:

GameObject myItem = (GameObject)Instantiate(Resources.Load("myPrefab"), typeof(GameObject));

Then you can access the Transform from the GameObject like this:

Transform transform = myItem.transform;

Solution 3

If you have the prefabs path like that

GameObject mainObject = (GameObject)Instantiate(Resources.Load("prefabs/" + "BaseMain"));
Share:
17,808
Mansa
Author by

Mansa

Updated on June 26, 2022

Comments

  • Mansa
    Mansa almost 2 years

    I am trying to figure out how to instantiate an prefab from c# code and i have tried the following:

    I have created an public Transform like so:

    public Transform myItem;
    

    I have then created an prefab and called it myPrefab and placed it in my Assets/Resources folder.

    I then in start() call this:

    myItem = Instantiate(Resources.Load("myPrefab")) as Transform;
    

    When running the code the Transform stays empty?

    What am I missing? Any help is appreciated.

  • Mansa
    Mansa over 9 years
    Thanks, I love to be badass ;-)