循环遍历 Transform 的子项时出错

Error while looping through child of Transform

我想遍历转换的所有子级,但出现错误。

这是我想要从中获取所有子项的变量:

public Transform parentToSearch;

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

稍后在脚本中我想遍历此转换的所有子项:

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: Cannot cast from source type to destination type

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

的形式访问它

改变

foreach (GameObject child in parentToSearch)

foreach (Transform child in parentToSearch)