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

如何在Unity中实现按下鼠标按键取消所有子Object的隐藏状态

解决方案

以下分两种常用场景给出可直接落地的实现方式:

场景1:点击场景中对应Object时,显示其所有子对象

  • 首先给需要检测点击的目标Object挂载对应碰撞体:3D物体挂Collider,2D物体挂Collider2D,非触发需求不要勾选Is Trigger
  • 场景主相机挂载Physics Raycaster(3D场景)或Physics 2D Raycaster(2D场景)组件
  • 新建C#脚本,挂到目标Object上,代码参考如下:
using UnityEngine;

public class ShowChildrenOnClick : MonoBehaviour
{
    // 可在Inspector面板修改触发的鼠标按键:0=左键 1=右键 2=中键
    public int triggerMouseButton = 0;

    private void OnMouseDown()
    {
        // includeInactive设为true才能检索到已隐藏的子对象
        foreach (Transform child in transform.GetComponentsInChildren<Transform>(includeInactive: true))
        {
            child.gameObject.SetActive(true);
        }
    }
}

提示:如果不需要显示父对象本身,只需要在遍历逻辑里加判断if(child != transform)即可过滤父节点。


场景2:按下指定鼠标按键时,显示提前预设的Object的所有子对象

  • 新建C#脚本,挂到场景内任意常驻节点(例如GameManager、主相机)上:
using UnityEngine;

public class ShowTargetChildrenOnPress : MonoBehaviour
{
    // Inspector面板拖入你要操作的目标Object
    public GameObject targetObject;
    public int triggerMouseButton = 0;

    private void Update()
    {
        if (Input.GetMouseButtonDown(triggerMouseButton) && targetObject != null)
        {
            foreach (Transform child in targetObject.transform.GetComponentsInChildren<Transform>(includeInactive: true))
            {
                child.gameObject.SetActive(true);
            }
        }
    }
}

常见问题排查

  • 点击无响应:优先检查目标Object碰撞体是否正常启用、主相机Raycaster组件是否挂载、脚本是否挂载到正确节点
  • 深层嵌套子对象未显示:确认GetComponentsInChildren的includeInactive参数设为了true,默认参数只会返回激活状态的对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 23:06:07