Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

"Simulated" mouse click?

Discussion in 'Immediate Mode GUI (IMGUI)' started by bigkahuna, Apr 20, 2009.

  1. bigkahuna

    bigkahuna

    Joined:
    Apr 30, 2006
    Posts:
    5,434
    Is there a (preferably easy) way to make a GUI.Button display as though it was mouse clicked without using a mouse? I've created a GUI.Button that triggers a function if clicked on, and I've also added an Input.GetButtonDown that triggers the same function. The problem is that if the user uses the mouse there is is a visual cue (the button looks depressed) if the button is clicked with a mouse, but there isn't a visual cue if a keystroke is used instead. Is there a way to tell a GUI.Button that it's been clicked on?
     
  2. Shaneo

    Shaneo

    Joined:
    Apr 2, 2009
    Posts:
    50
    This will make it look like the button is pressed while you hold down return.

    Code (csharp):
    1.  
    2. GUIStyle style = GUI.skin.GetStyle("Button");
    3. if( Input.GetKey(KeyCode.Return) )
    4.     style.Draw( new Rect(0,0,50,20), "Button", true, true, false, false );
    5. else
    6.     style.Draw( new Rect(0,0,50,20), "Button", false, false, false, false );
    7.  
    8.  
     
  3. bigkahuna

    bigkahuna

    Joined:
    Apr 30, 2006
    Posts:
    5,434
    Perfect, thanks. Here's my snippet for both mouse and keystroke:
    Code (csharp):
    1. var style;
    2.  
    3. function OnGUI () {
    4.     style = GUI.skin.GetStyle("Button");
    5.     if (Input.GetKey(KeyCode.Return)) {
    6.         style.Draw( new Rect(0,0,50,20), "Button", true, true, false, false );
    7.         print ("key pressed");
    8.     }
    9.     else {
    10.         style.Draw( new Rect(0,0,50,20), "Button", false, false, false, false );
    11.         if (GUI.Button (Rect (0, 0, 50, 20), "Button")) {
    12.             print ("mouse clicked");
    13.         }      
    14.     }
    15. }
     
  4. Shaneo

    Shaneo

    Joined:
    Apr 2, 2009
    Posts:
    50
    Looks good. You could probably get rid of the call to Draw in the else statement if you have the button right after it. I just put it in so the button would show up without a key pressed.

    Code (csharp):
    1.  
    2. else {
    3.       if (GUI.Button (Rect (0, 0, 50, 20), "Button")) {
    4.          print ("mouse clicked");
    5.       }
    6. }
    7.  
    Just saves drawing the button twice :D
     
  5. bigkahuna

    bigkahuna

    Joined:
    Apr 30, 2006
    Posts:
    5,434
    Got it, thanks! :)