How To Exclude Element From ForEach Loop

Hey,

I was wondering if theres a simple way to exclude an element from a foreach loop,

Basically i have a bunch of game objects in an array and i want to transform them all apart from one is there a way to do this

  1. Make a new List without that element.
  2. Add an if statement in the loop.
  3. Use For Loop and avoid the index if you know its position.
1 Like

this is what continue statements are good for. Lets you skip a iteration based on any condition you want.

foreach(var item in items) {
    if (item == ignoredItem) continue;
    // do loop stuff
}
2 Likes

hey so what exactly would i write for the ignoreditem
i tried this but it doesnt work

 foreach (GameObject Top in Top)
{
if (Top == Top[7]) continue;
//stuff
}

I’m not surprised!

Let’s keep our variable names straight… this would make perhaps more sense:

foreach (GameObject Top in Tops)
{
   if (Top == Tops[7]) continue;

//....
1 Like