- Home /
Determining GUI button pressed
I have 2 for loops set up creating a grid of GUI buttons according to some variables. All of the buttons are created using one if(GUI.button(...)) line contained in a for loop.
After creating this, I am completely stumped on how to determine which button is being pressed for my inventory functions. Are there ways of assigning IDs to buttons? Or some other way of assigning values?
The way the Unity devs seem to have written the GUI kind of works against what I'm doing as buttons are created as well as checked for input in a single if statement. You can create them without the if statement but I don't know how to check if the button is pressed from there.
Answer by Eric5h5 · Nov 29, 2012 at 01:37 AM
You can use the index of the loop.
I'm trying to do something like this, have a vote for now
Answer by BPPHarv · Nov 29, 2012 at 01:39 AM
This is kinda hackish but if you have a local variable that increments inside the for loop each button action can then include this number in it's onclick actions.
for (var x: int=0;x < numberOfButtons;x++)
{
if(GUI.button())
{
updateInventory(x);//where x will be the number of this button
}
}
If you're using a for each loop where you don't already have a handy index/count variable you just initialize a local variable to 0 before the loop and increment it at the end of the loop. The following is pseudo code.
var x:int=0;
for(var in collection)
{
if(GUIButton())
{
updateInventory(x);
}
x++;
}
Edit : doh beaten by a min by the master himself.. basically this is a more elaborate verson of what eric5h5 posted above.