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;
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;
如果你有这样的预制路径
GameObject mainObject = (GameObject)Instantiate(Resources.Load("prefabs/" + "BaseMain"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.