- Home /
How to make each button load a different number with out cycling
I have this foreach loop going through OnGUI and create a button for each of my colors I have for my cube to change to. As for right now, it just cycles through 0-4 , but I want to be able to click a button and have it change to that color without cycling through the numbers.
Update: I tried out a for loop in the OnGUI area and it works up to a point. It does work, but it just sets the ColorID at 4 and the value won't change afterwards. How can I make it so when I click one of the 5 buttons it changes to that int. Example, I press button 1 and it changes the ColorID to 1
private void OnGUI()
{
float Offset = 0;
foreach (Material M in ColorMaterial)
{
if(GUI.Button (new Rect(10, 40 + Offset, 200, 50), M.name))
{
for (int i = 0; i < ColorMaterial.Length; i++)
{
ColorID = i;
if (M.name.Equals("Color_" + ColorID))
{
rend.sharedMaterial = M;
}
}
}
Offset += 100;
}
}
Answer by bobisgod234 · Apr 21, 2017 at 03:57 AM
Change the foreach loop to a for loop
for(int j = 0; j < ColorMaterial.length; j++)
replace instances of M with
ColorMaterial[j]
For example,
if(GUI.Button (new Rect(10, 40 + Offset, 200, 50), M.name))
becomes
if(GUI.Button (new Rect(10, 40 + Offset, 200, 50), ColorMaterial[j].name))
remove the inner for loop, and just assign j to ColorID
ColorID = j;
rend.sharedMaterial = ColorMaterial[j];
Your answer
Follow this Question
Related Questions
problem with gui 2 Answers
GUI.Button not showing up 1 Answer
GUI.Toolbar - Custom on/off button states 2 Answers
How do i use foreach/for loops properly? 1 Answer
Gui Buttons 2 Answers