[英]Error while looping through child of Transform
I want to loop over all children of a transform but I am getting an error. 我想遍历转换的所有子项,但出现错误。
This is the variable I want to get all the children from: 这是我要从中获取所有子项的变量:
public Transform parentToSearch;
Then I dragged in the editor a Transform object from the Hierarchy to the script into parentToSearch
. 然后,我在编辑器中将一个Transform对象从Hierarchy拖到了
parentToSearch
脚本中。
Then later in the script I want to loop over all childs of this Transform: 然后,在脚本的后面,我想遍历此Transform的所有子元素:
private void OnGUI()
{
if (hasDescription == true && clickForDescription == true)
{
foreach (GameObject child in parentToSearch)
{
if (child.GetComponent<ItemInformation>() != null)
{
ItemInformation iteminformation = child.GetComponent<ItemInformation>();
if (child.name == objectHit)
{
var centeredStyle = GUI.skin.GetStyle("Label");
centeredStyle.alignment = TextAnchor.UpperCenter;
GUI.Label(new Rect(Screen.width / 2 - 50, Screen.height / 2 - 25, 100, 50), iteminformation.description, centeredStyle);
}
}
}
}
}
The exception is on the line: 唯一的例外是:
foreach (GameObject child in parentToSearch)
This is the error: 这是错误:
InvalidCastException: Cannot cast from source type to destination type
InvalidCastException:无法从源类型转换为目标类型
The parentToSearch
variable is a type of Transform
since it is declared as public Transform parentToSearch;
parentToSearch
变量是一种Transform
类型,因为它被声明为public Transform parentToSearch;
. 。 It's also an enumerator and when you use it in a
foreach
loop, you are accessing each child item in the array one by one. 它也是一个枚举器,当您在
foreach
循环中使用它时,您正在逐一访问数组中的每个子项。 You must access it as a Transform
not as a GameObject
. 您必须将其作为
Transform
而不是GameObject
。
Change 更改
foreach (GameObject child in parentToSearch)
to 至
foreach (Transform child in parentToSearch)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.