Search Unity

Buttons on cycle

Discussion in 'Scripting' started by ArrSoft, Apr 16, 2014.

  1. ArrSoft

    ArrSoft

    Joined:
    Apr 14, 2014
    Posts:
    10
    Hello!
    I parse "items" from DB (names, id, description, icon) from inventory. In inventory I write cycle which make buttons and then icons.
    I want icons grid. I don't know how to write this.
    In real:
    $in_real.jpg

    All right:
    $All_right.jpg

    P.S. Sorry for my bad English
     
  2. zehreken

    zehreken

    Joined:
    Jun 29, 2009
    Posts:
    112
    Something like this will do the job.

    Code (csharp):
    1.  
    2. int buttonWidth = 50;
    3. int buttonHeight = 50;
    4. int offset = 5;
    5. for (int i = 0; i < rowCount; i++)
    6. {
    7.  for (int j = 0; j < columnCount; j++)
    8.  {
    9.   if (GUI.Button(new Rect(j * buttonWidth + offset, i * buttonHeight + offset, buttonWidth, buttonHeight), "Label"))
    10.   {
    11.    // Do something
    12.   }
    13.  }
    14. }
    15.  
    Google nested loops and grids.
     
  3. ArrSoft

    ArrSoft

    Joined:
    Apr 14, 2014
    Posts:
    10
    It work a bit wrong.
    I parse items from BD, and show them in cycle via "foreach".
    I use this.
    Code (csharp):
    1.  
    2. for (int i = 0; i < 5; i++){
    3.              for (int j = 0; j < 7; j++) {
    4.                 foreach(string img in image){
    5.                     if(img=="purseico")icon=purse_ico;
    6.                     if(img=="noneico")icon=none_ico;
    7.                     GUI.Button (new Rect(j * buttonWidth + offset, i * buttonHeight + offset, buttonWidth, buttonHeight), icon);
    8.                 }
    9.             }
    10.         }
    11.  
    Buttons are really located grid. But showed 7 buttons instead 1 button in one slot, since their DB 7.
    Screen:
     
  4. ArrSoft

    ArrSoft

    Joined:
    Apr 14, 2014
    Posts:
    10
    I corrected this problem :)

    Code (csharp):
    1.  
    2. foreach(string img in image){
    3.             if(img=="purseico")icon=purse_ico;
    4.             if(img=="noneico")icon=none_ico;
    5.             if(j<7){
    6.                     j++;
    7.                     if(j==7&i<5){
    8.                         j = 0;
    9.                         i++;
    10.                     }
    11.             }
    12.             GUI.Button (new Rect(j * buttonWidth + offset, i * buttonHeight + offset, buttonWidth, buttonHeight), icon);
    13.         }
    14.  
    Thank you!