Search Unity

Destroying RectTransform

Discussion in 'Scripting' started by SparrowGS, Jul 10, 2018.

  1. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Hey, so i'm trying to destroy an object made out of 4 components, RectTransform, CanvasRenderer, Image, CustomScript.

    when i try to destroy it i get the message "Can't remove RectTransform because Image (Script) depends on it"

    goggled all over the place to no avail.

    this is the ONLY destroy call in the project.

    Code (CSharp):
    1.     public void Clear(){
    2.         foreach (Transform t in statsParent.transform) {
    3.             Destroy (t.gameObject);
    4.         }
    5.     }
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    So it stopped doing that after resetting unity, must be one of these compilation hiccups or something.

    2017.4.3 BTW
     
  3. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
    Have you accidentally used
    Destroy(t)
    instead of
    Destroy(t.gameObject)
    ?
     
  4. dadude123

    dadude123

    Joined:
    Feb 26, 2014
    Posts:
    789
    Destroying a Transform or RectTransform is a common pitfall, you should never ever do that.
    To completely destroy an object, always make sure to destroy the
    .gameObject
    .

    You can destroy other components however. For example you could do Destroy(g.GetComponent<Renderer>())
    which will just remove the Mesh or Sprite renderer (or whatever renderer there is) component on the gameobject, and leave the gameobject itself and all the other components it has intact.


    Your code looks right, but the message you get tells us that there's some other code somewhere that does it wrong.

    Maybe you have some code somewhere that does something like this:
    Destroy( transform.GetChild(n) )

    which will cause the problem as well, since GetChild returns a Transform and not the GameObject!

    The GameObject is the "actual" object, everything else is just a component on the GameObject (including Transforms, Renderers, ...)