Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading PreFab from c# in Unity

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.

like image 559
Mansa Avatar asked Sep 16 '25 01:09

Mansa


1 Answers

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;
like image 136
apxcode Avatar answered Sep 19 '25 09:09

apxcode