- Home /
 
Change GUI.Box color when click button
Hi, I have 1 GUI.Box and 3 GUI.Buttons, I want to change on run time the text and the color of the GUI.Box depending on the button clicked. How can I do that? I have tried but no luck, here is my NON working code.
void OnGUI() { GUIStyle textFieldStyle = new GUIStyle();
 string text;
 text="";
     if (GUI.Button (new Rect (Screen.width * .01f, Screen.height * .24f, Screen.width * .32f, Screen.height * .24f), "RED")){
         textFieldStyle.normal.textColor = Color.red;
         text = "RED";
     }
     if (GUI.Button (new Rect (Screen.width * .34f, Screen.height * .24f, Screen.width * .32f, Screen.height * .24f), "YELLOW")){
         textFieldStyle.normal.textColor = Color.yellow;
         text = "YELLOW";
     }
     if (GUI.Button (new Rect (Screen.width * .67f, Screen.height * .24f, Screen.width * .32f, Screen.height * .24f), "BLUE")){
         textFieldStyle.normal.textColor = Color.blue;
         text = "BLUE";
     }
     GUI.Box(new Rect (Screen.width * .01f, Screen.height * .01f, Screen.width * .98f, Screen.height * .22f), text, textFieldStyle);
 }
 
               Thanks!
Answer by zharik86 · Feb 19, 2014 at 06:37 PM
Unfortunately, if to use standard GUI.Box, its color of a texture practically can't be changed (because a texture almost black with an alpha the channel to 50%). Though text color changes. So, at first it is necessary to create, for example, in Photoshop, a white texture of 16x16 in size. To make the style for GUI.Box on the basis of the made texture. And to add the following code in your script:
  public GUIStyle mystylebox = null; // your new style for box
  private Color colorbox = Color.white;
  void OnGUI() {
   GUI.color = Color.white;
   if (GUI.Button (new Rect (Screen.width * .01f, Screen.height * .24f, Screen.width * .32f, Screen.height * .24f), "RED")) {
    colorbox = Color.red;
    text = "RED";
   }
   if (GUI.Button (new Rect (Screen.width * .34f, Screen.height * .24f, Screen.width * .32f, Screen.height * .24f), "YELLOW")) {
    colorbox = Color.yellow;
    text = "YELLOW";
   }
   if (GUI.Button (new Rect (Screen.width * .67f, Screen.height * .24f, Screen.width * .32f, Screen.height * .24f), "BLUE")) {
    colorbox = Color.blue;
    text = "BLUE";
   }
   GUI.color = colorbox;
   GUI.Box(new Rect (Screen.width * .01f, Screen.height * .01f, Screen.width * .98f, Screen.height * .22f), text, mystylebox);
  }
 
               I hope it to you helped.
Your answer
 
             Follow this Question
Related Questions
GUI style causing problem 0 Answers
Defualt GUI Style 1 Answer
GUIStyle for GUI.label doesn't work for android? 1 Answer
Is Mesh Collider Optimal for GUI? 2 Answers
proper inventory system issue.. 1 Answer