Creating and destroying Unity3D

I need to create an instance and destroy the assembly file in a run. I tried:

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 this?

+6
source share
4 answers

You do not need to declare your instance as an object if you get an ancestor object, because it does not have a transforma component.

 public GameObject prefab; GameObject obj = Instantiate(prefab); 

if you want to get the transform component, just enter obj.transform if you want to destroy the Destroy(obj); object type Destroy(obj);

Hope this helps the world

+3
source

gives the transform and the transform component cannot be destroyed

Destroy the GameObject to which the Transform component is bound:

 GameObject.Destroy(o.gameObject); 

Instantiate returns the same type of object that is passed as a parameter. Since this is a Transform , you cannot use it for a GameObject . Try the following:

 GameObject o=((Transform)Instantiate(prefab)).gameObject; 
+3
source

Your codes do not make sense.

 public Transform prefab; Object o = Instantiate(prefab); 

Are you creating a transformation? Why aren't you trying to add an assembly instead?

You must try:

 public GameObject prefab; // attach the prefab in Unity Editor GameObject obj = Instantiate(prefab); GameObject.Destroy(obj); 
+1
source

I noticed that the accepted answer is actually erroneous.

When using the Instantiate function of the MonoBehaviour class , we must indicate the type of what we are creating. I highly recommend reading the Create API Link .


To create a prefix as a GameObject

 GameObject g = Instantiate(prefab) as GameObject; 

To create a prefix as a Transform and provide a position in three-dimensional space.

 Transform t = Instantiate(prefab, new Vector3(1,10,11), new Quaternion(1,10,11,100)); 

Destroy a component, which means that you can destroy scripts attached to gameObjects, as well as hard devices and other components.

 Destroy(g); 

or

 Destroy(t.gameObject) 

0
source

Source: https://habr.com/ru/post/951508/


All Articles