【问题标题】:Unity how to set a prefab property trought an arrayUnity如何通过数组设置预制属性
【发布时间】:2022-11-10 06:23:15
【问题描述】:

你能帮我写出正确的语法吗?我坚持以下代码:

GameObject cube = (GameObject)Instantiate(cube_prefab, new Vector3(x, y, 0), Quaternion.identity, transform);

cube.GetComponentInChildren<TextMeshPro>.text = "test" **// WORKS FINE**

考虑到在我的预制件里面我有更多TextMeshPro,所以我的问题是:如果我无法通过数组访问,我如何才能到达第二个对象?对我来说听起来很奇怪


cube.transform.GetChild(0).GetComponent<TextMeshPro>().text = "AAA"  // DOESN'T WORK

提前致谢

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    GetChild(int) 方法是transform 的方法。在您的示例中,您改为从 GameObject 调用 GetChild(0)。因此,您示例中的修复将使用“立方体”的transform 属性,找到子项,然后获取子项的组件:

    GameObject cube = (GameObject)Instantiate(cube_prefab, new Vector3(x, y, 0), Quaternion.identity, transform);
    
    cube.GetComponentInChildren<TextMeshPro>.text = "test" **// WORKS FINE**
    
    cube.transform.GetChild(0).GetComponent<TextMeshPro>.text = "test"
    

    这是 GetChild(int) 的 Unity docs

    如果你想为你的游戏对象迭代下一级子级,你可以这样做:

    var t = cube.transform;
    var childCount = t.childCount;
    for ( int i = 0; i < childCount; i++ )
    {
        if ( t.GetChild(i).TryGetComponent<TextMeshPro> ( out var tmp ) )
        {
            tmp.text = $"TextMeshPro found on child {i}";
        }
    }
    

    请注意,这只会遍历“立方体”的直接子代,而不是那些子代的子代。您必须检查每个孩子的孩子数才能进一步检查家谱。

    【讨论】:

      【解决方案2】:

      对不起,如果我听起来像是在说教,但似乎你只是试图猜测语法是什么,而不知道每件事的真正作用,这对你没有任何好处。您应该研究具有泛型的方法(尤其是如何调用它们)并尝试有意义地编写代码,而不是到处乱扔括号,并期望事情会发生。

      有了这个,让我们看看你的问题。

      1. 当前上下文中不存在名称“GetChild”,因为您的多维数据集属于GameObject 类型,它确实没有GetChild 方法。拥有它的组件是Transform。你应该这样称呼它:cube.transform.GetChild(0)...

      2. 如果你解决了这个问题,下一个问题是 GetChild 方法不使用泛型 (<Type>),即使它使用了,首先你应该在尖括号中提供一个类型,然后将常规括号 () 写入表示方法调用。你可能想要的是先得到孩子,然后得到一个组件:cube.transform.GetChild(0).GetComponent&lt;TextMeshPro&gt;().text = "test";

      3. cube.GetComponentInChildren&lt;TextMeshPro&gt;.GetChild(0).text 中,您错过了括号:cube.GetComponentInChildren&lt;TextMeshPro&gt;().GetChild(0).text。更重要的是,TextMeshPro 没有 GetChild 方法,您一定对方法调用的顺序感到困惑。

      4. cube.GetComponentInChildren&lt;TextMeshPro&gt;[0] 中,您尝试像使用数组一样使用语法,而 GetComponentInChildren 只是一种方法,而不是数组的属性。

        要尽快回答您的问题:使用yourGameObject.transform.GetChild(childIndex).GetComponent&lt;TextMeshPro&gt;().text transform.GetChild() 向下导航到您想要的游戏对象,然后才调用 GetComponent(记住括号!)以获取您的文本属性。

      【讨论】:

      • 感谢您的帮助,但这仍然不起作用 cube.transform.GetChild(0).GetComponent<TextMeshPro>().text = "test";
      • 我更新了问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2021-11-24
      • 2012-12-04
      • 1970-01-01
      相关资源
      最近更新 更多