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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With