foreach loop stops at first item

hi! i have this is script and my foreach is not working properly, when i try to debug something inside it, it works perfectly, but if i put a if or for inside it, it only goes through it once

public List<GameObject> allExercises = new List<GameObject>();
public string[] exercisesSplitString;

public void LoadData()
    {
          foreach(GameObject item in allExercises)
                {
                    Debug.Log("hoo");
                    if(item.name == exercisesSplitString[0])
                    {
                        Debug.Log("heeey");
                    }
                }

Some things to consider:

  • the first item name in allExercises IS the same as exercisesSplitString[0]
  • it doesn’t debugs the ‘heeey’, only the ‘hoo’ and only once
  • if i erase the ‘if’, it debugs the ‘hoo’ correctly (which is 5 times)
  • obviously i’m not only trying to debug things, but i’m trying with debug to see if i can fix it before doing what i want to

thank you so much!

i tried something different to see if the foreach works

foreach(GameObject item in allExercises)
                {
                    Debug.Log("heey");
                    if(2 == 2)
                    {
                        Debug.Log("hoo");
                    }
                }

i know it seems weird to compare 2 and 2, but it actually worked. then i tried this:

foreach(GameObject item in allExercises)
                {
                    Debug.Log("heey");
                    if(2 == 2)
                    {
                        Debug.Log("hoo");
                        GameObject.Find("1").GetComponent<Toggle>().isOn = true;
                    }
                }

and the foreach only worked once and didn’t turn the toggle i wanted on.

I have faced a similar problem. My solution was to simply use a coroutine instead. For example, in your case you could do:

IEnumerator LoadData(){
         foreach(GameObject item in allExercises){
                     Debug.Log("hoo");
                     if(item.name == exercisesSplitString[0]){
                         Debug.Log("heeey");
                         yield return null;
                     }else{
                         //whatever you wanna do
                         yield return null;
                     }
          }
}

And you could simply call this coroutine via:

StartCoroutine(LoadData());

in whichever function you wish.