GUI.SelectionGrid() how to detect if a button was pressed

SelectionGrid returns a number even if nothing is pressed, how do I detect that user has pressed a button ?

Hello,

IIRC, SelectionGrid assumes one of the buttons is always selected and it just returns the index of that selected button. So there is no “onclick” type events just a return that tells you which button within the grid is selected.

what is a common situation where you would use it ?

Hopefully someone else can jump in here as I’ve never found a use for it. :wink:

(then again, maybe that is the answer)

You can’t detect if a selected grid button has been clicked again when using GUI.SelectionGrid. You have to monitor the clicks and find the rectangle in which each click occurs.

I just use if (GUI.Changed) to check it an event happened and then check the index

I’ve seen people taling about using it for inventory screens. I can see ways it would be used for puzzle games, too.

How do I get the rectangle of a selected button ?

I think you just have to figure it out yourself (if the bounds is X wide and you know there are two buttons in your grid then you can figure out the bounds for each button).

This is one of the reasons why I haven’t used this particular function – it seems easier to just make your own at this point :wink:

Except if your selection grid is bigger than the screen and uses a scrollbar it will report GUI.Changed when you touch the scrollbar to view more of the selection.

dude…take the example.

int _ClickedToolBarIndex = 0;
string[ ] _ToolBarStrings = new string[ ] {“Option 1”, “Option 2”, “Option 3”, “Cancel”};

void OnGUI()
{
_ClickedToolBarIndex = GUI.Toolbar (new Rect (200, 5, 750, 15), _ClickedToolBarIndex, _ToolBarStrings);
if(_ClickedToolBarIndex == 0)
{
//do it
}
if(_ClickedToolBarIndex == 1)
{
//do that
}
if(_ClickedToolBarIndex == 2)
{
///take it
}
if(_ClickedToolBarIndex == 3)
{
//take that
}
if(_ClickedToolBarIndex == 4)
{
///good bye
}
}

hi,

i know this is an really old threat… but i figure that there are some people who may need this.
at least… i did.
and i found a way to fix this.

1 Like

Hello guys

Without any workaround just set you returned int to “-1” after proccessing:

int selInt = 0; // I have zero here and everything is ok, but anyway, try initialize with "-1"
public void OnGUI()
{
    selInt = GUILayout.SelectionGrid(selInt,...);
    if (selInt...)
    {
        //some action according to your business logic
    }
     selInt = -1;
}