Unity中Instantiate一个prefab时需要注意的问题

Unity中Instantiate一个prefab时需要注意的问题,第1张

在调用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 function Instantiate ( 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)命令是一样的,并移动到指定的位置。如果一个游戏物体,组件或脚本实例被传入,实例将克隆整个游戏物体层次,以及所有子对象也会被克隆。所有游戏物体被激活。

首先要区分开这两个物体,用Instantiate克隆后,通过改名字,tag,或者加代码编号等方式,来区分每一个克隆物体,比如名字改为obj01,obj02能区分后,当他们同时进入触发器时,在触发代码中计数number++;如果number+2就是同时进入,+1就是有先后,判断出同时进入后,只处理name=="obj01"的物体当然你可以写的灵活一些,最好在代码中来编号区分克隆体

这个方法你试一下吧,其实我也没试过

不行的话告诉我原因,我再想想

public GameObject prefab1;//先把金币做成预设物 GameObject go= (GameObject)Instantiate(prefab1);//用这句创建这个预设物 gotransformposition用来设置位置 Destroy (名字 );//用来删除金币 int b=RandomRange(1,10);//随机数

方法一 因为 Transform 实现了 IEnumerable 接口,所以可以用 foreach (Transform child in transform) 遍历子对象,对比 transformgameObject 的 type 是不是你的 prefab 的 type 方法二 用 Object 的 FindObjectsOfType(),

以上就是关于Unity中Instantiate一个prefab时需要注意的问题全部的内容,包括:Unity中Instantiate一个prefab时需要注意的问题、unity中从一个prefab生成的两个物体同时进入触发器,如何只获得一个、unity中怎么控制生成的prefab位置等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9507275.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-29
下一篇2023-04-29

发表评论

登录后才能评论

评论列表(0条)

    保存