是否可以从父级获取游戏对象嵌套子项?
地图Gameobject如下所示:
ListProcess (ListProcessItem1) => item1 => 1 => ItemIcon
例如Iam使用此代码:
itemslot = GameObject.FindGameObjectWithTag ("ListProcessItem1").gameObject;
GameObject item = itemslot.gameObject.transform.GetChild(0).gameObject;
GameObject child = item.gameObject.transform.GetChild(0).gameObject;
GameObject sitemImage = child.gameObject.transform.GetChild(0).gameObject;
当我运行代码时出现错误:
UnityException: Transform child out of bounds
LakeMainProcess.generatePrize1 () (at Assets/script/fishing/LakeMainProcess.cs:48)
LakeMainProcess.Start () (at Assets/script/fishing/LakeMainProcess.cs:21)
注意: 我只能到达游戏对象(1)。游戏对象(ItemIcon)出错。
我该如何解决?
答案 0 :(得分:1)
用这个替换你的块:
Debug.Log("A " + GameObject.FindGameObjectWithTag ("ListProcessItem1") == null);
var itemslot = GameObject.FindGameObjectWithTag ("ListProcessItem1").gameObject;
Debug.Log("B " + itemslot.gameObject.transform.GetChild(0) == null);
GameObject item = itemslot.gameObject.transform.GetChild(0).gameObject;
Debug.Log("C " + item.gameObject.transform.GetChild(0) == null);
GameObject child = item.gameObject.transform.GetChild(0).gameObject;
Debug.Log("D " + child.gameObject.transform.GetChild(0) == null);
GameObject sitemImage = child.gameObject.transform.GetChild(0).gameObject;
它会告诉你哪些对象无法找到。我打赌它是FindGameObjectWithTag
,你确定这个对象有这个确切的标签吗?
或者更简单地使用:
var ico = GameObject.FindGameObjectWithTag("ListProcessItem1").transform.FindChild("item1/1/ItemIcon").GetComponent<WhateverYouNeed>();