Why is my foreach loop getting Inactive GameObjects! Unity 2020.3.24f1

I Do not Understand, I Thought This Would Only Happen If the Item Is Active!
Please Help, This Is Happening Every Time I Run The Code {Its In Update Btw, and only one item is active}

7734351--971691--Problem.PNG

 foreach(GameObject go in Items){
            if(go.activeInHierarchy && activeItems.Count < Items.Length){
                activeItems.Add(Items[activeCurrentIndex]);
                activeCurrentIndex += 1;
                Debug.Log(activeCurrentIndex);
                if(activeCurrentIndex >= Items.Length){
                    activeCurrentIndex = 0;
                }
            }
        }

7734351--971691--Problem.PNG
7734351--971691--Problem.PNG
7734351--971700--947826-b638677c4974af534f5053e6f1eb04b7.png

Once you drag something into the Items array, it’s there.

If you want to ask if it is active or not, you can do so with:

Is it possible you only disabled a Component on the item, not the actual GameObject?

1 Like

You may be confusing foreach with the various GameObject.Find... methods?
The GameObject.Find... methods will only return objects that are active in the scene, but that is completely irrelevant to how objects are enumerated in a foreach loop.

A foreach loop simply loops over a collection of things. It doesn’t care what those things are or what kinds of properties/values/states/etc. they have.

1 Like

Firstly thank you for the response, second i have already tried that way and it does the same thing. I’ve been using unity for 4 years and never had this problem. Starting to think it may just be the scripting api in this version! Thank you anyway

Will the find methods work for looping through each of the objects in the array?

I’m not really sure how to answer this.
Finding objects in the scene and looping through objects in a collection are two entirely different things.

You’re already assigning objects in your array from the inspector, so there’s not really any reason to use a Find method.

Add some more log statements in your loop to verify the activeInHierarchy and activeSelf values of each GameObject in the Items array are what you expect them to be:

foreach(GameObject go in Items) {
  Debug.Log($"Object: {go.name}, activeInHierarchy: {go.activeInHierarchy}, activeSelf: {go.activeSelf}");

  if(go.activeInHierarchy && activeItems.Count < Items.Length) {
    activeItems.Add(go);
  }
}

Are your objects active before entering play mode, and become inactive after entering play mode? And if so, does this loop run in Start or Awake?
Because it’s likely then the loop is running before the object(s) get a chance to disable, and this would be a script execution order issue in that case.