Let’s say I have a scene as follows: MainCamera Canvas --Image ----Panel
Where Canvas, Image, and Panel are all UI elements. I would like to delete the Panel object entirely through c#. Here’s what did:
Destroy(image.transform.GetChild(0).gameObject); Debug.Log(parent.transform.childCount); //Still logs 1 even though I just deleted it
I thought that maybe it was just deleting the gameObject and not the entire thing so I tried:
Destroy(image.transform.GetChild(0)); //Gives me an error saying that the image script relies on the //rect transform for the image object and therefore can't be deleted Debug.Log(parent.transform.childCount);
What should I do? There must be a way to destroy UI elements like this.
-Have you tried attaching that script to a GO (GameObject)?
-Have you tried calling Destroy() in the Start-/Awake-function, to test
it?
-Have you tried creating a Method and calling it, when you press a certain
button (either UI or on your
keyboard)?
-Have you checked if the hierarchical structure is correct (in specific I
mean the inheritence-tree of each
GO)?
And here’s a little tip: If you try to destry a GameObject, always explicitely express that in the Destroy()-call, like this: Destroy(myGO.gameObject);. Doing this might save you some headaches.
However, if you try destroying a script (or anything from a GO, without destroying the GO itself) use GetComponent (you know how GetComponent works. I would like to show, but due to inline-HTML formatting I can’t properly use >< these brackets…).
Super late, but I just saw this when I ran into this problem.
Destroy(image.transform.GetChild(0).gameObject); Debug.Log(parent.transform.childCount); //Still logs 1 even though I just deleted it
The Destroy statement is right and is why the second version doesn’t work. To destroy the actual object you need to send in the gameobject. I think your debug statement is just telling you the wrong thing. I’m not sure what parent is referring to, but if it is the parent of the Image (the Canvas) then it makes sense that transform.childCount is equal to 1 because you just deleted the panel.