You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何从父物体Floor遍历子物体并修改坐标与激活状态?

问题:批量修改Floor子物体Unit的坐标与Cube状态

我需要修改Floor下所有Unit的坐标,同时停用Unit里的部分Cube。不想通过硬编码逐个声明public GameObject unit1;这种方式,因为对象太多了。我把脚本挂在Floor上,想在void Start()里遍历这些对象来修改,但所有尝试都失败了。

我试过这段代码,但修改Transform数组里的内容没法改变游戏内对象的坐标,其他加载子物体的方式也都没用:

Transform[] units = new Transform[floorObject.transform.childCount];

for (int i = 0; i < floorObject.transform.childCount; i++)
{
    units[i]= floorObject.transform.GetChild(i);
}

解决方法

1. 直接遍历修改(最简单可靠)

你的代码只是把Transform引用存进数组,但没执行实际的坐标修改操作。直接在遍历过程中修改即可,不用额外存数组:

void Start()
{
    // 遍历Floor的所有直接子物体(即各个Unit)
    foreach (Transform unitTrans in transform)
    {
        // 修改Unit的局部坐标(相对于Floor的位置),示例:重置到X轴偏移i的位置
        unitTrans.localPosition = new Vector3(unitTrans.GetSiblingIndex() * 2, 0, 0);
        
        // 遍历当前Unit下的所有子物体,筛选Cube并停用指定项
        foreach (Transform cubeTrans in unitTrans)
        {
            // 假设Cube的名字包含"NeedDisable"就停用,可根据实际条件调整
            if (cubeTrans.name.Contains("NeedDisable"))
            {
                cubeTrans.gameObject.SetActive(false);
            }
        }
    }
}

注:脚本挂在Floor上时,transform就是Floor自身的Transform,无需额外定义floorObject。

2. 用标签/组件精准筛选

如果Unit和Cube有统一的标签(比如给Unit设标签Unit,Cube设标签Cube),可以用更灵活的方式批量获取:

void Start()
{
    // 获取Floor下所有层级的Unit(仅保留直接子物体的话用上面的foreach)
    foreach (Transform unitTrans in GetComponentsInChildren<Transform>())
    {
        // 确认是Floor的直接子物体,避免误改嵌套的其他对象
        if (unitTrans.parent == transform && unitTrans.CompareTag("Unit"))
        {
            unitTrans.position = new Vector3(0, 0, unitTrans.GetSiblingIndex() * 3); // 修改世界坐标
            
            // 找到当前Unit下的所有Cube
            foreach (GameObject cube in unitTrans.GetComponentsInChildren<GameObject>())
            {
                if (cube.CompareTag("Cube"))
                {
                    // 示例:停用索引为奇数的Cube
                    if (cube.transform.GetSiblingIndex() % 2 != 0)
                    {
                        cube.SetActive(false);
                    }
                }
            }
        }
    }
}

3. 常见坑点排查

  • 确认脚本确实挂在激活状态的Floor对象上
  • 区分localPosition(相对父物体坐标)和position(世界坐标),别用错
  • 如果Unit是动态生成的,要确保Start()执行时对象已经生成;如果是异步加载,要在加载完成回调里执行遍历逻辑

内容的提问来源于stack exchange,提问作者EeEe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 08:48:15