- Home /
Question by
Kirbsssys · Oct 07, 2021 at 02:53 AM ·
uiinstantiateif-statementsdestroy object
How do I destroy the object that was instatiated
I wanna know how I can destroy the game object that was instantiated
if (previousRockAmount == 0)
{
if (previousRockAmount != rockAmount)
{
GameObject obj = Instantiate(rockImage, Vector3.zero, Quaternion.identity, transform);
obj.GetComponent<RectTransform>().localPosition = GetPosition(itemIdentifier - 1);
obj.GetComponentInChildren<TextMeshProUGUI>().text = rockAmount.ToString("n0");
previousRockAmount = rockAmount;
if (rockAmount == 0)
{
Destroy(obj);
}
}
}
Comment
your code is fine, you destroy it with the Destroy(obj) method
I think you should write, rockAmount=previousRockAmount; for the rockamount will be 0 unless u are using it anywhere else.
Answer by rh_galaxy · Oct 07, 2021 at 11:08 AM
You don't save a reference to the obj, so you don't know what to destroy later. Also you sometimes delete the object the same frame it is created, is this what you want?
private GameObject obj; //declare a reference to obj at class level
//private GameObject rocks[] = new GameObject[3]; //declare a list of max 3 rocks at class level
...
obj = Instantiate()
...
Then when you are done with the object do
Destroy(obj);