2 for-loops, one counting to 7, other to 3, why?

Hey,

I was programming a list, which gives a bit of their objects to other lists:

        for (int i = 0;i < spawnerLocations.Length; i++)
        {
            spawnerLocations[i].ingridientsToSpawn.Clear();

            int f = ingridients.Count / spawnerLocations.Length;
            while (spawnerLocations[i].ingridientsToSpawn.Count != f)
            {
                int r = Random.Range(0, ingridients.Count);
                spawnerLocations[i].ingridientsToSpawn.Add(ingridients[r]);
                ingridients.RemoveAt(r);
                Debug.Log(spawnerLocations[i].ingridientsToSpawn.Count);
            }
        }

Both should have 7 objects in their lists, because the ingridients list has 14 elements, but one of them, the second one, has only 3

I’m not sure what you’re saying exactly. You only have 1 for loop there.

Also, use Debug.Log calls to make sure everything has the right values you think they should when it should.

Once you remove 7 items you have 7 remaining in the ingredients list. So then int f = ingridients.Count / spawnerLocations.Length; on the second attempt will give you 3 because 7 / 2 is 3.

Sounds like you really want to calculate f before the outer loop and only once.

2 Likes