在调用Instantiate()方法使用prefab创建对象时,接收Instantiate()方法返回值的变量类型必须和声明prefab变量的类型一致,否则接收变量的值会为null.
比如说,我在脚本里面定义:
publicGameObject myPrefab;
那么在使用这个myPrefab做Instantiate()的时候,接收返回值变量的类型也必须是GameObject,如下:
GameObject newObject = Instantiate(myPrefab) as GameObject;
注意Instantiate()后面的as也要是GameObject。
又比如我们的prefab类型是我们自定义的UserObject,
publicUserObject prefab;
那么在使用Instantiate()时我们需要写成:
UserObject newObject = Instantiate(myPrefab) as UserObject;
比较容易犯的一个错误是我们声明的类型是:
publicGameObject myPrefab;
在Instantiate()返回值却想要用Transform,如下:
Transform newObject = Instantiate(myPrefab) as Transform;
这个时候就会出现newObject为null的问题。
附注官方API资料:
Object.Instantiate 实例
static functionInstantiate(original: Object,position:Vector3,rotation: Quaternion) : Object
Description描述
Clones the object original and returns the clone.
克隆原始物体并返回克隆物体。
Clones the object original, places it at position and sets the rotation to rotation, then returns the cloned object. This is essentially the same as using duplicate command (cmd-d) in Unity and then moving the object to the given location. If a game object, component or script instance is passed, Instantiate will clone the entire game object hierarchy, with all children cloned as well. All game objects are activated.
克隆原始物体,位置设置在position,设置旋转在rotation,返回的是克隆后的物体。这实际上在Unity和使用复制(ctrl+D)命令是一样的,并移动到指定的位置。如果一个游戏物体,组件或脚本实例被传入,实例将克隆整个游戏物体层次,以及所有子对象也会被克隆。所有游戏物体被激活。