- Home /
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.
Why don't you do
Debug.Log("Item name: " + item.name + " | exercise name: " + exercisesSplitString[0]);
and compare the 2 to find difference :)
just tried that, this time it didn't sent me the 'hoo' nor the things i asked in this new debug, i feel like there's something wrong with the foreach, could you check my comment bellow? i tried other things and it didn't work either
It's unclear what you are trying to achieve.
I see this:
public List allExercises = new List();
But if you initialize it in the inspector you don't need the = new List<GameObject>();
part.
Is the public string[] exercisesSplitString;
initialized anywhere? Are you sure you are not getting any errors in the console?
Answer by bentoBAUX · Feb 14 at 02:35 PM
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.
I don't think this is a solution to the problem, it only spreads the loop to do one item per frame instead of doing it all in one go.