- Home /
Destroying an Instantiated GameObject
I am creating a lives system that uses GUI as indicators - duh.
When you die, the current GUI is destroyed using the Destroy(GameObject) function. However, since the GUI is in the hierarchy and is only Instantiated in the scene, the Destroy() function tries to destroy the hierarchy object, which leads to a system error. It works fine enough, but I think the constant stream of errors is what causes the game to crash when run as an EXE.
How do I destroy the instance of the object, but not the object itself?
Answer by Muuskii · Aug 07, 2012 at 08:12 PM
You could use GameObject.FindGameObjectsWithTag to find them in order to destroy them. But I guess the question is; why are you using separate GameObjects as GUI instead of calling DrawTexture inside of OnGUI
Thank you.
Answer by Mander · Aug 07, 2012 at 08:17 PM
How do I destroy the instance of the object, but not the object itself?
what u have in the hierarchy tab is what u see in our scene/game tab. if u don't want to erase forever ur GUI make it a prefab and instantiate it. then u can always erase it and re instantiate it again.
Answer by xwolfhunter · Aug 10, 2012 at 11:55 AM
I ended up just using raycasts, for any future viewers who want to know how I fixed the problem.
Answer by Meltdown · Aug 10, 2012 at 06:05 PM
You need to create a reference to the instance and assign it to a variable.
i.e
[SerializeField] GameObject _myPrefab;
var myObject = GameObject.Instantiate(_myPrefab, Vector3.zero, Quaternion.Identity);
Destroy(myObject);