循环通过Transform的子时出错

问题描述 投票:1回答:1

我想遍历转换的所有子项,但我收到错误。

这是我想让所有孩子来自的变量:

public Transform parentToSearch;

然后我在编辑器中将一个Transform对象从Hierarchy拖到脚本中,然后拖到parentToSearch

然后在脚本中我想循环遍历此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);
                    }
                }
            }
        }
    }

例外是在线:

foreach (GameObject child in parentToSearch)

这是错误:

InvalidCastException:无法从源类型转换为目标类型

c# unity3d unity5
1个回答
5
投票

parentToSearch变量是一种Transform,因为它被声明为public Transform parentToSearch;。它也是一个枚举器,当你在foreach循环中使用它时,你将逐个访问数组中的每个子项。您必须以Transform身份访问它,而不是GameObject

更改

foreach (GameObject child in parentToSearch)

foreach (Transform child in parentToSearch)
© www.soinside.com 2019 - 2024. All rights reserved.