foreach 语句不能对 UnityEngine.GameObject 类型的变量进行操作

foreach statement cannot ooperate on variables of type UnityEngine.GameObject

正如标题所说,这是我的问题。我尝试了两种不同的解决方法:

首先是这段代码:

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

这在 foreach 循环内的 var 上给了我 Unknown Resolve Error

第二个是这个:

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

这让我的标题有误。

我该怎么办?我到处查看如何通过名称在 object 中获取 object,到处都是通过第一个示例完成的。

foreach 仅适用于实现 IEnumeratorIEnumerable.

的事物

GetComponentInChildren<T>() returns 单个 T,在您的示例中,您将 GameObject 作为 T 传递,但是 GameObject 不是你可以迭代的东西(即它不根据 docs 实现 IEnumeratorIEnumerable)。

也许您打算将不同的东西传递给 GetComponentInChildren<T>()?我不太熟悉 Unity 或你想要完成的事情,但 GameObject 确实有一个名为 GetComponentsInChildren<T>() 的方法(注意名称中的复数形式),也许这就是你要找的东西?

GetComponentInChildren<T>() only returns a single result, whereas what you want is GetComponentsInChildren<T>(),其中 returns 所有给定类型。

你想要的是 Transform 组件,而不是 GameObject 类型(顺便说一句,它不是组件)。此外,正如@Keith Nesbitt 指出的那样,请注意 GetComponentsInChildren

处的 s
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 ;
    }
} ) ;