Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

foreach loop check a bool array?

Discussion in 'Scripting' started by derkoi, Jan 4, 2014.

  1. derkoi

    derkoi

    Joined:
    Jul 3, 2012
    Posts:
    2,255
    I have an array of game objects and an array of bools, I'm trying to instantiate the game objects if the bool is true but it's not working.

    Here's what I have so far...

    Code (csharp):
    1.  
    2.     public bool[] itemOwned;
    3.     public GameObject[] items;
    4.     int itemNumber = -1;
    5.  
    6.  
    7.  
    8.     public void setUpGear(){
    9.  
    10.     foreach (GameObject item in items){
    11.    
    12.             itemNumber += 1;
    13.  
    14.                if(itemOwned[itemNumber]){
    15.  
    16.                       //instantiate code here
    17.  
    18.                                         }
    19.                                      else
    20.                                           {
    21.                                            break;
    22.                                            }
    23.                                        }
    Can anyone help please?
     
  2. Amon

    Amon

    Joined:
    Oct 18, 2009
    Posts:
    1,384
    The whole post was rendered as html for some reason with all the tags showing.

    Basically:

    if ( itemOwned[itemNumber] == 0 ) /false/-1
    Continue
    //Instantiate code here


    The 'Continue' command basically returns the loop back to the start of the next iteration if itemOwned[itemNumber] is equal to 0, or whatever value you use to check if it is false.

    if it is equal to 0 anything after the Continue command is skipped because Continue breaks out the loop and continues on to the next iteration.
     
    Last edited: Jan 4, 2014
  3. derkoi

    derkoi

    Joined:
    Jul 3, 2012
    Posts:
    2,255
    Works perfect, thanks Amon.
     
  4. jgodfrey

    jgodfrey

    Joined:
    Nov 14, 2009
    Posts:
    564
    Untested, but simpler / cleaner...

    Code (csharp):
    1. foreach (GameObject item in items)
    2. {
    3.    itemNumber++;
    4.    if (itemOwned[itemNumber])
    5.    {
    6.       // Instantiate here
    7.    }
    8. }