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?
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.
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.
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.
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);
.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With