C# 实例化和销毁 Unity3D
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18176587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Instantiate and Destroy Unity3D
提问by Temp Id
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?
那么怎么做呢?
采纳答案by BilalDja
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.
你不必将你的实例声明为对象,如果你得到了它没有转换组件的祖先对象。
public GameObject prefab;
GameObject obj = Instantiate(prefab);
If you want get transform component just type obj.transform
.
If you want destroy the object type Destroy(obj);
.
如果你想获得转换组件,只需输入obj.transform
.
如果要销毁对象类型Destroy(obj);
。
回答by Heisenbug
gives transform and transform component cannot be destroyed
给出变换和变换组件不能被破坏
Destroy the GameObject
to which the Transform
component is attached to:
破坏GameObject
到的Transform
组分附着:
GameObject.Destroy(o.gameObject);
Instantiate
method returns the same type of the object passed as parameter. Since it's a Transform
you can't cast it to GameObject
. Try this:
Instantiate
方法返回作为参数传递的对象的相同类型。由于它是 aTransform
你不能将它投射到GameObject
. 尝试这个:
GameObject o=((Transform)Instantiate(prefab)).gameObject;
回答by xuanweng
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);
回答by xuanweng
I noticed the accepted answer is actually wrong.
我注意到接受的答案实际上是错误的。
When using the Instantiate function of the MonoBehaviourclass we must specify the type of what we are instantiating. I highly recommend reading Instantiate API reference.
当使用MonoBehaviour类的 Instantiate 函数时,我们必须指定我们正在实例化的类型。我强烈建议阅读Instantiate API 参考。
To instantiate a prefab as a GameObject
将预制件实例化为游戏对象
GameObject g = Instantiate(prefab) as GameObject;
To instantiate a prefab as a Transformand provide a position in 3D space.
将预制件实例化为Transform并在 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.
销毁组件,这意味着您可以销毁附加到游戏对象以及刚体和其他组件的脚本。
Destroy(g);
or
或者
Destroy(t.gameObject)