2017-06-14 85 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>()(注意名称中的复数形式)的方法,也许这就是你要找的?

相关问题