Unity GameObjects在被销毁后仍然在层次结构中显示

时间:2016-12-04 18:18:27

标签: c# xml unity3d

我有一些以编程方式创建的Text对象,我想在我更新它们的XML列表后删除它们。出于某种原因,它们不会被删除。它们仍然显示在层次结构中。

XML只是一个带有根元素的文件和带有名称属性的播放器元素。

以下是代码:

public GameObject textTemplate;
public InputField nameInput;

// list of player names
private List<GameObject> players = new List<GameObject>();

private const string playersPath = "foo/bar.xml";

// this is a button OnClick callback
public void TryAddNew()
{
    // get name from input field
    string name = nameInput.text;

    if (players.FirstOrDefault(t => t.GetComponent<Text>().text == name) == null)
    {
        // update XML

        XDocument doc = XDocument.Load(playersPath);

        XElement root = doc.Element("players");
        root.Add(new XElement("player",
            new XAttribute("name", name)
        ));

        doc.Save(playersPath);

        LoadPlayers();
    }
}

private void LoadPlayers()
{
    // destroy existing player texts
    foreach (GameObject obj in players)
    {
        // THE PROBLEM IS HERE, this doesn't seem to work
        UnityEngine.Object.Destroy(obj.GetComponent<Text>());
        UnityEngine.Object.Destroy(obj);
    }
    players.Clear();

    // load players from XML

    XDocument users = XDocument.Load(playersPath);

    XElement root = users.Element("players");

    int i = 0;

    foreach (XElement playerEle in root.Elements("player"))
    {
        CreateNewPlayerText(playerEle.Attribute("name").Value, i);
        i++;
    }
}

// instantiate new player text
private void CreateNewPlayerText(string name, int index)
{
    GameObject newObj = Instantiate(textTemplate) as GameObject;

    // insert into parent view
    newObj.transform.SetParent(textTemplate.transform.parent);

    Text newText = newObj.GetComponent<Text>();
    newText.text = name;
    newText.rectTransform.anchoredPosition = new Vector2(SCROLL_MARGIN, -SCROLL_MARGIN - index * 15);

    // show text
    newObj.SetActive(true);
}

1 个答案:

答案 0 :(得分:0)

我从未将文本GameObjects添加到列表中。我不得不将它添加到CreateNewPlayerText方法的末尾:

players.Add(newObj);