- Home /
Right-click button using GUI class?
Hey, I am trying to use the standard GUI class to implement buttons... As far as just clicking them, everything was pretty easy:
function OnGUI { var myButton = GUI.Button(Rect(), myString)
if(myButton) { //Do something crazy } }
However, if I want something different to happen when the user right-clicks the button, how could that be done? I'm thinking something like:
function OnGUI { var myButton = GUI.Button(Rect(), myString)
if(myButton) { if(mouseButton1) { //Action 1 } else { //Action 2 } } }
Does that make sense? If it does, how do I implement it "correctly"?
Answer by jonas-echterhoff · May 18, 2010 at 01:27 AM
You'll want to look at the current GUI event to see which button was pressed. Try this code:
if (GUILayout.Button("MyButton")
{
if (Event.current.button == 0)
Debug.Log ("MyButton was clicked with left mouse button.");
else if (Event.current.button == 1)
Debug.Log ("MyButton was clicked with right mouse button.");
}
Can I also add keyboard modifiers to that? (Like holding ctrl)? Well, I guess I can, but how? :P
if (Event.current.control) Debug.Log ("Ctrl was held");
Answer by Tobias · May 17, 2010 at 11:48 AM
Maybe sth like that?
private var actives = false; private var actives2= false;
function OnMouseDown () { if(Input.GetMouseButton(1)){ actives = actives ? false : true; } if(Input.GetMouseButton(0)){ actives2= actives2 ? false : true; } }
function OnGUI () { if (actives) { GUI.Label (Rect (50,50,100,50), "test"); } if (actives2) { GUI.Label (Rect (50,50,100,50), "test"); } }
That seems to require that I create every button as a separate object in the hierarchy, and attach this script to them individually? I'm going to have 20+ buttons in the final application, so that seems a bit excessive... :/
Or am I misunderstanding this completely?
Why you have buttons in your hierarchy? This script creates the buttons. Just attach this to your main camera and add enough buttons into the javascript code. Or do I misunderstand sth?
Ah, I see now... But it is still a kind of "backwards" way of doing it, compared to what I've been scripting so far. Thanks for your answer though. :)
Answer by ramsey05 · Oct 06, 2021 at 04:54 PM
actives = actives ? false : true;
means
actives = !actives;