簡體   English   中英

Unity3D:在重定孩子時遍歷孩子的問題

[英]Unity3D: Issue in looping through the children while reparenting them

我試圖將一個GameObject的所有子代更改為另一個。

foreach (Transform child in transform) {
child.parent = new_parent.transform;
}

此代碼部分分離了子項,並將幾個子項保留在原始父項中。 我使用以下代碼執行上述操作。

foreach (Transform child in transform) {
    child.tag = "collected";
}

GameObject[] collected = GameObject.FindGameObjectsWithTag ("collected");
foreach (Transform child in collected.transform) {
    child.transform.parent = new_parent.transform;
}

這完美地工作。 我還與parent.GetChild(i)一起使用,發生了類似的問題。 我在哪里想念?

正如評論中所解釋的,項目丟失了,因為您在使用“ foreach”進行迭代的同時修改了子級集合。 總的來說,這是一個壞主意,在遍歷集合時,切勿修改集合(除非您確切地知道自己在做什么)。

您找到的一種解決方案是制作該集合的副本,遍歷該副本,然后安全地從原始集合中刪除項目。 標記對象然后調用FindGameObjectsWithTag效率低下,因為它會在每個FindGameObjectsWithTag中進行搜索,並且容易出錯(如果您忘記刪除標簽,則會產生奇怪的行為)。 您最好列出一個清單:

var collected = new List<Transform>();
foreach (var child in transform) {
    collected.Add(child);
}
foreach (Transform child in collected) {
    child.transform.parent = new_parent.transform;
}

在這種情況下,更簡單的方法是使用while循環刪除最后一個孩子,只要其父母有任何孩子:

while (transform.childCount > 0) {
    transform.GetChild(transform.childCount - 1).parent = new_parent.transform;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM