Mansa
Mansa

Reputation: 2325

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.

Upvotes: 4

Views: 18513

Answers (3)

gitstar
gitstar

Reputation: 51

If you have the prefabs path like that

GameObject mainObject = (GameObject)Instantiate(Resources.Load("prefabs/" + "BaseMain"));

Upvotes: 2

axwcode
axwcode

Reputation: 7824

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;

Upvotes: 8

Jay Kazama
Jay Kazama

Reputation: 3277

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;

Upvotes: 6

Related Questions