Object.Instantiate
public static Object Instantiate(Object original);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
//实例化Prefab
例1:
public GameObject prefab;
void Start() { for (int i = 0; i < 10; i++) Instantiate(prefab, new Vector3(i * 2.0f, 0, 0), Quaternion.identity); }//
例2:Transform theClonedExplosion;theClonedExplosion = Instantiate(explosion) as Transform;
//脚本里面定义:
public GameObject PrefabNo;
那么,在使用这个PrefabNo做Instantiate()的时候,接收返回值变量的类型必须是GameObject:
GameObject newObject = Instantiate(myPrefab) as GameObject;
又比如prefab类型是自定义的UserObject,
public UserObject prefab;
那么在使用Instantiate()时我们需要写成:
UserObject newObject = Instantiate(myPrefab) as UserObject;
注:比较容易犯的一个错误是声明的类型是GameObject:
public GameObject myPrefab;
在Instantiate()返回值却想要用Transform,如下:
Transform newObject = Instantiate(myPrefab) as Transform;
这个时候就会出现newObject为null的问题。
来源:https://www.cnblogs.com/Cocomo/p/5634930.html