[英]foreach statement cannot ooperate on variables of type UnityEngine.GameObject
So as title says, this is my problem. 因此,正如标题所述,这是我的问题。 I tried 2 different ways of solving it: 我尝试了两种解决方法:
First is with this code: 首先是这段代码:
var children = GetComponentInChildren<GameObject>();
foreach(var child in children)
{
if(child.name == "HealthBar")
{
HealthBar = child;
}
}
Which gives me Unknown Resolve Error
on var
inside foreach
loop. 这使我在foreach
循环内的var
上出现Unknown Resolve Error
。
Second is this: 其次是:
var children = GetComponentInChildren<GameObject>();
foreach(GameObject child in children)
{
if(child.name == "HealthBar")
{
HealthBar = child;
}
}
Which gives me error in the title. 这给了我标题错误。
What should i do? 我该怎么办? Everywhere i looked how to get object inside object by name, everywhere is done by first example. 我到处都在寻找如何按名称获取对象内的对象,到处都是通过第一个示例完成。
What you want is the Transform
component, not the GameObject
type (which is not a component by the way). 您需要的是Transform
组件,而不是GameObject
类型(顺便说一句,它不是组件)。 Moreover, as @Keith Nesbitt indicated, mind the s
at GetComponentsInChildren
此外,正如@Keith Nesbitt指出的那样,请注意GetComponentsInChildren
的s
var children = GetComponentsInChildren<Transform>();
foreach(var child in children)
{
if(child.name == "HealthBar")
{
HealthBar = child;
}
}
An extension method you could try : 您可以尝试的扩展方法:
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
only works on things that implement IEnumerator
or IEnumberable
. foreach
仅适用于实现IEnumerator
或IEnumberable
。
GetComponentInChildren<T>()
returns a single T
, in your example you pass in GameObject
as the T
, however GameObject
is not something you can iterate over (ie it does not implement IEnumerator
or IEnumberable
according to the docs ). GetComponentInChildren<T>()
返回一个T
,在你的榜样,你在通过GameObject
的T
,但是GameObject
是不是你可以遍历(即不落实IEnumerator
或IEnumberable
根据文档 )。
Perhaps you meant to pass something different into GetComponentInChildren<T>()
? 也许您打算将其他内容传递给GetComponentInChildren<T>()
? I am not too familiar with Unity or what you are trying to accomplish, but GameObject
does have a method called GetComponentsInChildren<T>()
(note the plural in the name), maybe that's what you are looking for? 我对Unity或您要完成的任务不太熟悉,但是GameObject
确实有一个名为GetComponentsInChildren<T>()
(请注意名称中的复数形式),也许这就是您要寻找的?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.