how to write OnMouseDown() condition for GUI button

Hi to all…
i want to retrieve the code when i press the GUI button…

i tried like this…

function OnGUI(){
   if(GUI.Button(Rect(10,10,50,40),"Click")){
         Debug.Log("i want a value when i press the button");
    }
}

answer :
i got the output “i want a value when i press the button”.
this output came when i release the mouse.
But i want the output when i pressed…

please help me !!!

There are no real limitations in Unity’s GUI system :wink: This is how the GUI.Button function works internally:

public static bool Button(Rect position, GUIContent content, GUIStyle style)
{
	GUIUtility.CheckOnGUI();
	int controlID = GUIUtility.GetControlID(GUI.buttonHash, FocusType.Native, position);
	switch (Event.current.GetTypeForControl(controlID))
	{
		case EventType.MouseDown:
		{
			if (position.Contains(Event.current.mousePosition))
			{
				GUIUtility.hotControl = controlID;
				Event.current.Use();
			}
			return false;
		}
		case EventType.MouseUp:
		{
			if (GUIUtility.hotControl == controlID)
			{
				GUIUtility.hotControl = 0;
				Event.current.Use();
				return position.Contains(Event.current.mousePosition);
			}
			return false;
		}
		case EventType.MouseDrag:
		{
			if (GUIUtility.hotControl == controlID)
			{
				Event.current.Use();
			}
			break;
		}
		case EventType.Repaint:
		{
			style.Draw(position, content, controlID);
			break;
		}
	}
	return false;
}

Note: You can’t simply replicate all functions yourself since Unity uses some internal classes in their functions.

To detect a mousedown on a button you can do something like:

//C#
Event E = Event.current;
Rect R = new Rect( ... ); // your button position
if (GUI.Button(R,"text"))
{
}
if (E.type == EventType.MouseDown && R.Contains(E.mousePosition))
{
    // mouse down event
}

For GUILayout it might work this way:

//C#
Event E = Event.current;    
if (GUILayout.Button("text"))
{
}
Rect R = GUILayoutUtility.GetLastRect();
if (E.type == EventType.MouseDown && R.Contains(E.mousePosition))
{
    // mouse down event
}

Not sure if it works this way, but i guess it should

Yes, Unity’s GUI has these lovable little limitations, doesn’t it?

I’d check for it manually in Update():

void Update(){
	//Assumes "Fire1" is bound to left mouse button in the input settings.
	if(Input.GetButtonDown("Fire1")&&new Rect(10,10,50,40).Contains(Input.mousePosition))
		Debug.Log("I want a value when i press the button.");
}