jdo*_*doe 1 c# unity-game-engine unity5
我想遍历转换的所有子项,但我收到错误.
这是我想让所有孩子来自的变量:
public Transform parentToSearch;
Run Code Online (Sandbox Code Playgroud)
然后我在编辑器中将一个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);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
例外是在线:
foreach (GameObject child in parentToSearch)
Run Code Online (Sandbox Code Playgroud)
这是错误:
InvalidCastException:无法从源类型转换为目标类型
的parentToSearch变量是一种类型的Transform,因为它被声明为public Transform parentToSearch;.它也是一个枚举器,当你在foreach循环中使用它时,你将逐个访问数组中的每个子项.您必须以Transform不作为a的方式访问它GameObject.
更改
foreach (GameObject child in parentToSearch)
Run Code Online (Sandbox Code Playgroud)
至
foreach (Transform child in parentToSearch)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |