For loop work strangely

Hi all. I’ve got a strange problem. There are 5 caves with their ‘i’ IDs. The caves script has a list with a random enemy with the cave id, which is taken from the list of all types of enemies. At the entrance, the cave closes, and in order for it to open, all enemies with the ID of this cave must be killed. For convenience, enemy name = cave id. And here is the problem: the for loop returns only the number 4. I do not understand how and why this happens. The below code is called by the Create() method which is called in the Start() method.

        for (int i = 0; i < 5; i++)
        {
            var cave = Instantiate(caveTemplate, roomPos, Quaternion.identity);

            cave.name = i.ToString();

            if (i != 0)
            {
                var enemy = enemiesList[0];

                enemy.name = i.ToString();

                cave.GetComponent<Cave>().enemies.Add(enemy);
            }                                                                                                                                                                        
        }

i think, its happening beacuse of your if statement which doesnt take first element of for loop which is zero

two problems were noticed:

  • first, you are skipping the first cave if (i != 0)

  • seconde you are always working with the same enemy 0 var enemy = enemiesList[0];so this will get name of 1-2-3 and the final is 4 will stick to this. (I think you need to change it to var enemy = enemiesList*;*