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

时间:2017-06-14 16:13:33

标签: c# unity3d unity5

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

首先是这段代码:

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

Unknown Resolve Error循环varforeach给我var children = GetComponentInChildren<GameObject>(); foreach(GameObject child in children) { if(child.name == "HealthBar") { HealthBar = child; } }

其次是:

ConcreteBuilderA builder = ConcreteBuilderA.getBuilder();
ThingBeingBuilt thing;

builder.setValue(value);
builder.setConcreteValue(num);
thing = builder.build()

这让我在标题中出错。

我该怎么办?在任何地方我都看了如何通过名字在对象内部获取对象,到处都是第一个例子。

3 个答案:

答案 0 :(得分:3)

你想要的是Transform组件,而不是GameObject类型(顺便说一下,它不是一个组件)。此外,正如@Keith Nesbitt指出的那样,请注意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 ;
    }
} ) ;

答案 1 :(得分:2)

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

答案 2 :(得分:1)

IEnumberable仅适用于实施GetComponentInChildren<T>()T的内容。

GameObject会返回一个T,在您的示例中,您将GameObject作为IEnumerator传递,但IEnumberable不是您可以迭代的内容(即根据docs,它没有实现GetComponentInChildren<T>()GameObject

也许你打算将不同的东西传递给$("#submit").click(function(){ var fields = document.getElementsByClassName("checkBox"); for(a in fields){ var x = a.getAttribute("id"); console.log(x); } ?我对Unity不熟悉或者你想要完成什么,但是create external table test(id string,f_name string,l_name string,ts timestamp) STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler' WITH SERDEPROPERTIES ('hbase.columns.mapping' = ':key,amitesh:f_name,cf:l_name,:timestamp') TBLPROPERTIES('hbase.table.name' = 'test_rs'); 确实有一个名为GetComponentsInChildren<T>()的方法(请注意名称中的复数),也许那就是你在寻找什么为?