【问题标题】:Error while looping through child of Transform循环通过 Transform 的子级时出错
【发布时间】:2017-12-18 07:00:37
【问题描述】:

我想遍历一个变换的所有子节点,但出现错误。

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

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】:

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

改变

foreach (GameObject child in parentToSearch)

foreach (Transform child in parentToSearch)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2021-06-15
    相关资源
    最近更新 更多