从游戏对象中删除最后一个孩子

时间:2015-07-13 17:12:23

标签: c# list unity3d destroy

我为触摸屏应用程序创建自定义键盘,按下按钮时输出图像。然后,这些图像填​​充网格布局以保持线性组织。我需要一个退格按钮。我真的在退格时苦苦挣扎。我无法找到附带代码的问题。当我点击deleteKey按钮时没有任何反应,我不知道我在哪里出错但我希望它删除messagePanel游戏对象中的最后一个孩子。

List<GameObject> msgSymbols = new List<GameObject>();
public string prefabPath;
int msgLength;

Vector3 symbolPos;
GameObject symbolChar;
GameObject msgPanel;
Vector3 symbolScale = new Vector3(1.0f, 1.0f, 1.0f);

GameObject[] symbolKeys;
GameObject deleteKey;

void Awake()
{
    msgPanel = GameObject.FindGameObjectWithTag("MessagePanel");
    symbolKeys = GameObject.FindGameObjectsWithTag("SymbolKey");
    deleteKey = GameObject.FindGameObjectWithTag("DeleteKey");
}

#region IPointerClickHandler implementation

public void OnPointerClick (PointerEventData eventData)
{
    if (transform.CompareTag("SymbolKey"))
    {

        symbolChar = Instantiate(Resources.Load (prefabPath)) as GameObject;    // Instantiate an symbol
        symbolChar.transform.SetParent(msgPanel.transform);                     // Parent it to grid
        symbolChar.transform.localScale = symbolScale;                          // Set scale of all objects added
        symbolPos = symbolChar.transform.position;                              // Find position of objects in grid
        msgLength = msgPanel.transform.childCount;

        foreach(Transform t in msgPanel.transform)                              // Create running list of symbol objects added to messagePanel
        {
            msgSymbols.Add(t.gameObject); 
        }

        Debug.Log (msgLength);
    }

    else if (transform.CompareTag("DeleteKey"))
    {
        if(msgSymbols.Count == 0) return;
        Destroy(msgSymbols.LastOrDefault());

        // Old attempts

        // msgSymbols.RemoveAt(msgLength - 1);
        // Destroy(msgSymbols[msgSymbols.Count-1]);
    }

}
#endregion

2 个答案:

答案 0 :(得分:1)

如果count为0,则索引值为-1,超出索引范围。

if(messageSymbols.Count > 0) Destroy(messageSymbols.LastOrDefault());

答案 1 :(得分:1)

在删除之前检查该数组是否至少有1个值:

else if (transform.CompareTag("DeleteKey"))
{
    if(messageSymbols.Count == 0) return;
    Destroy(messageSymbols[messageSymbols.Count-1]);
}