2017-06-14 50 views
0

所以正如標題所說,這是我的問題。我試過2個不同的解決它的辦法:foreach語句不能對類型爲UnityEngine.GameObject的變量操作

首先是與此代碼:

var children = GetComponentInChildren<GameObject>(); 
foreach(var child in children) 
{ 
    if(child.name == "HealthBar") 
    { 
     HealthBar = child; 
    } 
} 

這給了我Unknown Resolve Errorvarforeach循環。

二是這樣的:

var children = GetComponentInChildren<GameObject>(); 
foreach(GameObject child in children) 
{ 
    if(child.name == "HealthBar") 
    { 
     HealthBar = child; 
    } 
} 

這給了我錯誤的稱號。

我該怎麼辦?無處不在我看着如何通過名稱獲得對象內的對象,到處都是通過第一個示例完成的。

+0

'GetComponentInChildren ()'返回一個'GameObject'實例?如果只返回一個對象,則不能/不需要循環。我不知道'GetComponentInChildren'是什麼,但也許你的意思是'GetComponentInChildren >()'? – KMoussa

+0

是的。我沒有注意到有'GetComponentsInChildren'。問題在於'S'。謝謝 –

回答

3

你想要的是Transform組件,而不是GameObject類型(它不是順便說明的一個組件)。此外,由於@Keith內斯比特表示,介意sGetComponentsInChildren

var children = GetComponentsInChildren<Transform>(); 
foreach(var child in children) 
{ 
    if(child.name == "HealthBar") 
    { 
     HealthBar = child; 
    } 
} 

擴展方法你可以嘗試:

public static void Traverse(this GameObject gameobject, System.Action<GameObject> callback) 
{ 
    Transform transform = gameobject.transform; 
    for (int childIndex = 0 ; childIndex < transform.childCount ; ++childIndex) 
    { 
     GameObject child = transform.GetChild(childIndex).gameObject; 
     child.Traverse(callback); 
     callback(child); 
    } 
} 

// ... 

gameObject.Traverse((go) => 
{ 
    if(go.name == "HealthBar") 
    { 
     HealthBar = go ; 
    } 
}) ; 
+0

這是最正確的答案 – Lestat

+0

'S'是我的問題,但是感謝這個'Traverse'方法。 –

1

foreach只適用於執行IEnumeratorIEnumberable的事情。

GetComponentInChildren<T>()返回一個T,在你的榜樣,你在GameObject通過爲T,但是GameObject是不是你可以遍歷(即不根據docs實施IEnumeratorIEnumberable)。

也許你打算把不同的東西傳給GetComponentInChildren<T>()?我不太熟悉Unity或你正在努力完成的任務,但GameObject確實有一個名爲GetComponentsInChildren<T>()(注意名稱中的複數形式)的方法,也許這就是你要找的?

相關問題