Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate and Destroy Unity3D

Tags:

c#

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?

like image 930
Temp Id Avatar asked Aug 11 '13 20:08

Temp Id


People also ask

What is destroy in Unity?

Description. Removes a GameObject, component or asset. The object obj is destroyed immediately after the current Update loop, or t seconds from now if a time is specified. If obj is a Component, this method removes the component from the GameObject and destroys it.

How do you destroy another object in Unity?

To destroy an object on collision within the using ty software, you have to use some form of the void OnCollisionEnter method. For 2D games you need the void OnCollisionEnter2D() method and the void OnCollisionEnter() method for 3D games.

What does instantiate mean Unity?

Instantiating means bringing the object into existence. Objects appear or spawn or generate in a game, enemies die, GUI elements vanish, and scenes are loaded all the time in the game. Prefabs are very useful when you want to instantiate complicated GameObjects or collection of GameObjects at run time.


2 Answers

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);.

like image 131
BilalDja Avatar answered Oct 06 '22 13:10

BilalDja


gives transform and transform component cannot be destroyed

Destroy the GameObject to which the Transform component is attached to:

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:

GameObject o=((Transform)Instantiate(prefab)).gameObject;
like image 22
Heisenbug Avatar answered Oct 06 '22 12:10

Heisenbug