Simple way to Delete the Last Child of a GameObjec

2019-07-13 20:04发布

问题:

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
}

回答1:

Solved it with this:

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



回答2:

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.