'check list of gameobject has active gameobject and insert into other list

i have a list of gameobject and I would like to check if each of those is currently active in the scene. The following is my code.

foreach (GameObject hazard in SceneHazard)
{
    //Check if hazard exist in the scene
    Debug.Log(hazard.name);

    if (hazard.activeInHierarchy)
    {
        Debug.Log(" is active");
        allActiveHazard.Add(hazard);
    }
    else
    {
        Debug.Log(" is NOT active");
    }
}

I also found other solution, which I've applied: https://stackoverflow.com/a/65934000/9425428 which would then be something like this:

allActiveHazard = SceneHazard.Where(obj => obj.activeInHierarchy).ToList();

but I still only get around two gameobjects inside the new list.

Variables assignment in inspector, the two list on the bottom are private

Active gameobjects in hierarchy

Console, somehow some gameobjects weren't checked?

Am I missing anything here? There are no other inactive parents from the screenshot provided



Solution 1:[1]

I added a few seconds delay before assigning the list. Probably somebody added animation to the GameObject.

StartCoroutine(Delay());

...
...

IEnumerator Delay()
{
    yield return new WaitForSeconds(0.1f);
    allActiveHazard = SceneHazard.Where(obj => obj.activeSelf).ToList();
}

Btw, I edited my code in response to @derHugo comment because I made some typos previously. Assigning inside the coroutine

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1