Search Unity

Resolved Loop through foreach and remove a value

Discussion in 'Scripting' started by Nixel2013, May 11, 2022.

  1. Nixel2013

    Nixel2013

    Joined:
    May 9, 2019
    Posts:
    143
    Hello

    How can I go through a foreach and "remove" the value that I don't want to use?

    I have the following:

    Code (CSharp):
    1. public Cubo[5] CubosSctips;
    2. public int ValueToSkip = 2;
    and I would like to go through the entire array and remove ValueToSkip value so that no code is executed in it

    Code (CSharp):
    1.     private void Start()
    2.     {
    3.         foreach (Cubo cubo in CubosSctips)
    4.         {
    5.             cubo.enabled = false;
    6.  
    7.         }
    8.     }
     
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    A small tip for developament,

    in case you need to change an Enumerator(List, Array etc.) runtime use List<T> as type for example, if you are sure that you dont need to change the Enumerator runtime, use an Array.

    By change i mean, remove or add an Item.

    In your case, everytime you remove or add an Item, you need to copy your array and expand or decrease it depending on your case.
     
  3. Nixel2013

    Nixel2013

    Joined:
    May 9, 2019
    Posts:
    143
    In my case it doesn't change, that's why I want to find the solution I asked above :)
     
  4. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Is
    ValueToSkip
    supposed to be the array index of
    CubosSctips
    ?
    If so, use a for-loop instead:
    Code (CSharp):
    1. for(int i = 0, i < CubosSctips.Length; i++)
    2. {
    3.   if(i != ValueToSkip)
    4.   {
    5.     CubosSctips[i].enabled = false;
    6.   }
    7. }
     
    Nixel2013 likes this.
  5. Nixel2013

    Nixel2013

    Joined:
    May 9, 2019
    Posts:
    143
    I love you <3