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

Double "for", buttons number.

Discussion in 'Scripting' started by antonioperez80, Sep 19, 2020.

  1. antonioperez80

    antonioperez80

    Joined:
    Jun 8, 2017
    Posts:
    40
    Hey!

    I am instantiating a grid with GUi.Buttons in an EditorWindow script with a "for" (columns) inside another "for" (rows). I would like that when you press a button, it tells me Debug.Log ("box number").

    I'm lousy at math.:(

    Code (CSharp):
    1.             for (int i = 0; i < columns; i++)
    2.             {
    3.                 for (int i2 = 0; i2 < rows; i2++)
    4.                 {
    5.              
    6.                     if (GUI.Button("button"))
    7.                     {
    8.                     Debug.Log("Button number");
    9.                     }
    10.  
    11.             }
    12.  
    13.             }
    Thank you!
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Hi @antonioperez80

    "I'm lousy at math"

    Luckily this has little to do with math... Even if this is Immediate mode GUI, you can capture the for loop variables into ints or a single Vector2 variable inside your loop and then use those in your button if block.
     
  3. antonioperez80

    antonioperez80

    Joined:
    Jun 8, 2017
    Posts:
    40
    I have it!

    Code (CSharp):
    1.     for (int i = 0; i < columns; i++)
    2.             {
    3.                 for (int i2 = 0; i2 < rows; i2++)
    4.                 {
    5.            
    6.                     if (GUI.Button("button"))
    7.                     {
    8.                     Debug.Log((i + (i2 * columns) );
    9.                     }
    10.             }
    11.             }