【问题标题】:Is it possible to get the gameobject nested child from parent with script?是否可以使用脚本从父级获取游戏对象嵌套的子级?
【发布时间】:2016-08-10 19:43:40
【问题描述】:

是否可以从 Parent 获取游戏对象 Nested Child ?

地图游戏对象如下:

ListProcess (ListProcessItem1) => item1 => 1 => ItemIcon

例如我正在使用此代码:

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 ) 出错了。

我该如何解决?

【问题讨论】:

    标签: c# unity3d


    【解决方案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>();
    

    【讨论】:

    • 是的@izeed,我错过了一些东西。游戏对象不是从 ListProcess 开始的。但它从 item1 => ListProcessItem1 开始。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多