Simple way to Delete the Last Child of a GameObject
Asked Answered
M

2

3

I'm trying to write a simple script that gets the child count of a GameObject and then destroys the last child (I want it to basically function like a delete key) but I'm getting the error: Can't remove RectTransform because Image (Script) depends on it. Can someone tell me how to resolve this?

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class DeleteSymbol : MonoBehaviour, IPointerClickHandler
{
    public GameObject deleteButton;
    public GameObject encodePanel;
    public GameObject decodePanel;

    #region IPointerClickHandler implementation

    public void OnPointerClick (PointerEventData eventData)
    {
        int numChildren = encodePanel.transform.childCount;             // get child count
        Debug.Log("There are " + numChildren + " children");

        if (numChildren > 0)
        {
            Destroy(encodePanel.transform.GetChild(numChildren - 1));       // destroy last child
        }
    }
    #endregion
}
Merill answered 4/9, 2015 at 16:38 Comment(0)
M
4

Solved it with this:

Destroy(encodePanel.transform.GetChild(numChildren - 1).gameObject);

Merill answered 4/9, 2015 at 16:46 Comment(0)
Q
4

The answer is that you need to destroy the game object itself, but your code tries tried to destroy the transform instead. The transform (and other components) may have dependencies that do not allow them to be destroyed in isolation. Unfortunately Unity provides the same method for destroying components and the game object itself, and an unhelpful error message if you pick wrong.

So the answer:

Destroy(encodePanel.transform.GetChild(numChildren - 1).gameObject);

is correct, and that's why.

Quirita answered 25/3, 2019 at 2:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.