kayra yorulmaz
kayra yorulmaz

Reputation: 67

How can you check which children are active within a parent in Unity?

I have a list of cameras under a "Cameras" parent:enter image description here

In my game, I want to set my character's relativity to whichever camera is active. For example, if Camera012 is active, then set the character's controls to be relative to Camera012. However, I don't know how to check through a parent object to see which children are setactive or not.

Upvotes: 2

Views: 6502

Answers (4)

Anouar Morad
Anouar Morad

Reputation: 1

public GameObject gameobject_I want to know;

print(gameobject_I want to know.transform.GetComponentsInChildren<Transform>().Length);

Upvotes: -1

derHugo
derHugo

Reputation: 90683

The drawback of GetComponentsInChildren (as suggested here) is that it also returns eventually further nested children and does not only look through the first level children.

Also activeInHierarchy (as suggested here) returns only true, if all parent in the Hierarchy of the examined object are also active.


In general You can iterate through all first level children of a GameObject by using

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

and check whether a child is active or not using

// 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!");
    }
}

this works also if any parent in the objects Hierarchy is inactive but the child itself active.

Upvotes: 2

Akin Erkan
Akin Erkan

Reputation: 321

If you just ask for children which are active its easy, if you want only one child a time add a sciprt to Cameras object that include

Camera firstactiveCamera = GetComponentInChildren<Camera>();

This will return only first active camera

If you want to find all active cameras in children then it turn back an array.

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

Diffrence is this is plural(Components) so you get all active camera objects in children.

Even if you want inactive objects in children then you can use

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

If you send true with function getcomponent it even find inactive objects and return them in array.

Upvotes: 2

vasmos
vasmos

Reputation: 2586

if (Camera002.activeInHierarchy) {
// do something
}

if you need you can add all camera to an array and use for loop to check each camera

Upvotes: 2

Related Questions