- Home /
Change Button GUIStyle on Click
Hi,
well I want know how can I do that?
void OnGUI() {
for(int x = 0; x<10; x++) {
if(GUI.Button(new Rect(10, 10*x, 100, 25), "Click me!", "label")) {
GUI.Box(new Rect(10, 10*x, 200, 25), "");
}
}
}
I had 10 buttons, so I can't use a boolean, because it will active all the boxes...
What can I do?
Thanks in advance. Bye.
PD: I need that for make a "focused" GUI element, but I don'w knwo how can I do that... So, somebody, can help me?
Answer by Tomer-Barkan · Dec 15, 2013 at 08:20 PM
You can hold an array of 10 booleans, and before displaying each button, change the style according to the matching boolean:
private bool[] clicked = new bool[10];
void Start() {
for (int i = 0; i > 10; i++) {
clicked[i] = false;
}
}
void OnGUI() {
for(int x = 0; x<10; x++) {
if (clicked[x]) {
// change style here
} else {
// default style here
}
if(GUI.Button(new Rect(10, 10*x, 100, 25), "Click me!", "label")) {
clicked[x] = true;
}
}
}
Edit: Since you only want one button marked at a time, instead of boolean array, it's better to have one int that will hold the number of the button that is clicked:
private int clicked = -1;
void Start() {
for (int i = 0; i > 10; i++) {
clicked[i] = false;
}
}
void OnGUI() {
for(int x = 0; x<10; x++) {
if (x == clicked) {
// clicked style here
} else {
// default style here
}
if(GUI.Button(new Rect(10, 10*x, 100, 25), "Click me!", "label")) {
clicked = x;
}
}
}
Oh! Thanks a lot!! Well I can't test it until tomorrow, so I need to know if it will stay changed only when I click it, or all time? As I see, It will stay changed at the time that I click the button or hold it.. So, how can I change it and conserve its focus on $$anonymous$$ouseButtonUp too?? Thanks in advance.
Since we're setting a class variable to true, it will remain true in the next frames as well, so clicking once will keep the bool true even after the click.
Then, each frame, we set the style for each button according to the bool, so if the bool remains true, the style for that specific button will remain changed.
Ok, that's all without having any bool? I think yes. But I need be sure... :P
In the second option we save the index of the clicked button, so it will remain changed until you click another button. Only one button is changed at a time.
The number acts as a bool I think... xD I like too much off-topic, so I will stop oftalking in 6/7 hours I will say you the results :P
Your answer
Follow this Question
Related Questions
GUI style causing problem 0 Answers
NullReferenceException in for-loop 0 Answers
Unity Hangs/Crash when remove GUI Button. 2 Answers
Semitransparent GUI Buttons 3 Answers
OnGUI button created by a foreach loop 4 Answers