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



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

首先是使用此代码:

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

这让我Unknown Resolve Error var循环内部foreach

二是这个:

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

这给了我标题错误。

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

你想要的是Transform组件,而不是GameObject类型(顺便说一下,它不是组件(。此外,正如@Keith内斯比特所指出的那样,请注意s GetComponentsInChildren

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 ;
    }
} ) ;

GetComponentInChildren<T>()只返回一个结果,而你想要的是 GetComponentsInChildren<T>() ,它返回所有给定的类型。

foreach只适用于实现IEnumeratorIEnumerable的东西。

GetComponentInChildren<T>()返回一个T,在您的示例中,您将GameObject作为T传入,但是GameObject不是您可以迭代的东西(即它不会根据文档实现IEnumeratorIEnumerable(。

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

最新更新