[英]Instantiate and Destroy Unity3D
I need to instantiate and destroy a prefab on the run. 我需要在运行中实例化并销毁预制件。 I tried these: 我试过这些:
public Transform prefab; //I attached a prefab in Unity Editor
Object o = Instantiate(prefab);
//using this I cannot get the transform component (I don't know why) so useless
Transform o=(Transform)Instantiate(prefab);
//gives transform and transform component cannot be destroyed
GameObject o=(GameObject)Instantiate(prefab);
//invalid cast
So how to do that? 那怎么办呢?
gives transform and transform component cannot be destroyed 赋予变换和变换组件不能被破坏
Destroy the GameObject
to which the Transform
component is attached to: 销毁Transform
组件所附加到的GameObject
:
GameObject.Destroy(o.gameObject);
Instantiate
method returns the same type of the object passed as parameter. Instantiate
方法返回与参数传递的对象相同的类型。 Since it's a Transform
you can't cast it to GameObject
. 由于它是Transform
,因此无法将其GameObject
Transform
为GameObject
。 Try this: 试试这个:
GameObject o=((Transform)Instantiate(prefab)).gameObject;
You don't have to declare your Instance as Object, if you do you get the ancestor object which it has not the transform component. 您不必将Instance声明为Object,如果您获得的是没有transform组件的祖先对象。
public GameObject prefab;
GameObject obj = Instantiate(prefab);
If you want get transform component just type obj.transform
. 如果你想获得变换组件,只需输入obj.transform
。
If you want destroy the object type Destroy(obj);
如果要销毁对象类型Destroy(obj);
. 。
Your codes does not make sense.. 你的代码没有意义..
public Transform prefab;
Object o = Instantiate(prefab);
You are instantiating a Transform? 你正在实例化变换? Why dont you try attaching the prefab instead? 为什么不尝试附加预制件呢?
You should try: 你应该试试:
public GameObject prefab; // attach the prefab in Unity Editor
GameObject obj = Instantiate(prefab);
GameObject.Destroy(obj);
I noticed the accepted answer is actually wrong. 我注意到接受的答案实际上是错误的。
When using the Instantiate function of the MonoBehaviour class we must specify the type of what we are instantiating. 当使用MonoBehaviour类的Instantiate函数时,我们必须指定我们实例化的类型。 I highly recommend reading Instantiate API reference . 我强烈建议您阅读Instantiate API参考 。
To instantiate a prefab as a GameObject 将预制件实例化为GameObject
GameObject g = Instantiate(prefab) as GameObject;
To instantiate a prefab as a Transform and provide a position in 3D space. 将预制件实例化为变换并在3D空间中提供位置。
Transform t = Instantiate(prefab, new Vector3(1,10,11), new Quaternion(1,10,11,100));
To Destroy a component, which means you can destroy scripts attached to gameObjects as well as rigibodies and other components. 销毁组件,这意味着您可以销毁附加到gameObjects的脚本以及rigibodies和其他组件。
Destroy(g);
or 要么
Destroy(t.gameObject)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.