Simple way to Delete the Last Child of a GameObject

可紊 提交于 2019-12-12 18:06:47

问题


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.



来源:https://stackoverflow.com/questions/32402833/simple-way-to-delete-the-last-child-of-a-gameobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!