【问题标题】:How can you check which children are active within a parent in Unity?在 Unity 中,如何检查父级中哪些子级处于活动状态?
【发布时间】:2020-05-03 07:33:07
【问题描述】:

我有一个“相机”父级下的相机列表:

在我的游戏中,我想将我的角色的相对性设置为哪个相机处于活动状态。例如,如果 Camera012 处于活动状态,则将角色的控件设置为相对于 Camera012。但是,我不知道如何检查父对象以查看哪些子对象是 setactive 的。

【问题讨论】:

    标签: c# unity3d parent children


    【解决方案1】:
    if (Camera002.activeInHierarchy) {
    // do something
    }
    

    如果您需要,您可以将所有摄像头添加到数组中并使用 for 循环检查每个摄像头

    【讨论】:

    • 您的答案非常接近完美,但是我希望您进一步澄清“将所有摄像头添加到数组并使用 for 循环检查每个摄像头”的意思。 :)
    • 你的意思是GameObject[] cameras = GetComponentsInChildren<GameObject>(); foreach (GameObject currentCam in cameras) { if (currentCam.activeInHierarchy) { camF = currentCam.transform.forward; camR = currentCam.transform.right; } }之类的吗?
    • 你可以做几种不同的方式,你可以在所有的相机和开始或唤醒 GameObject 相机上添加一个“相机”标签[] = GameObject.FindGameObjectsWithTag(“相机”);
    【解决方案2】:

    如果您只要求活动的孩子很容易,如果您一次只想要一个孩子,请添加一个包含

    的 Cameras 对象
    Camera firstactiveCamera = GetComponentInChildren<Camera>();
    

    这将只返回第一个活动的相机

    如果你想在孩子中找到所有活动的相机,那么它会返回一个数组。

    Camera[] activeCamerasInChildren = GetComponentsInChildren<Camera>();
    

    不同之处在于这是复数(组件),因此您可以在子项中获得所有活动的相机对象。

    即使你想在孩子中使用非活动对象,你也可以使用

    Camera[] activeCamerasInChildren = GetComponentsInChildren<Camera>(true);
    

    如果您使用函数 getcomponent 发送 true,它甚至会找到非活动对象并将它们返回到数组中。

    【讨论】:

    • 您的代码似乎在具有“相机”组件的父级中查找对象。我在问如何找到具有setactive(true)的子级
    • List activeGameobjects = new List(); for (int i = 0; i
    【解决方案3】:

    GetComponentsInChildren(建议here)的缺点是它最终还会返回更多嵌套的子级,并且不仅仅查看第一级子级。

    同样activeInHierarchy(如建议的here)仅返回true,如果检查对象的层次结构中的所有父对象也都处于活动状态。


    一般而言,您可以使用以下方法遍历游戏对象的所有第一级子级

    foreach(Transform child in someGameObject.transform)
    {
        // use child
    }
    

    并检查孩子是否正在使用

    // the object to examine the childs of
    Transform parent;
    
    // iterate through all first level children
    foreach(Transform child in parent)
    {
        if(child.gameObject.activeSelf)
        {
            Debug.Log($"The child {child.name} is active!");
        }
        else
        {
            Debug.Log($"The child {child.name} is inactive!");
        }
    }
    

    如果对象层次结构中的任何父级处于非活动状态但子级本身处于活动状态,这也有效。

    【讨论】:

      【解决方案4】:
      public GameObject gameobject_I want to know;
      
      print(gameobject_I want to know.transform.GetComponentsInChildren<Transform>().Length);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-07
        • 1970-01-01
        • 2011-08-12
        • 1970-01-01
        • 1970-01-01
        • 2018-02-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多