Mouse Detection on Unity 4.6's UI system

How to detect mouse right or left click to button on new UI System on 4.6

I needed that myself, so I forked Tim C.'s gist to create my own input handler. It requires ExtraMouseEvents.cs and IExtraMouseEventsHandler.cs to work. To use it, remove the Standalone Input Module component from the EventSystem in your scene, and add Mouse Input Module instead. Bonus feature: You can toggle drag support for the right and middle mouse buttons.

To use it you need to add scripts to your buttons/other controls which implement IRightPointerClickHandler, IRightPointerDownHandler, IRightPointerUpHandler, IMiddlePointerClickHandler, IMiddlePointerDownHandler or IMiddlePointerUpHandler. Example:

using UnityEngine;
using UnityEngine.EventSystems;

public class RightTest : MonoBehaviour, IRightPointerClickHandler
{
	public void OnRightPointerClick(PointerEventData data)
	{
		Debug.Log("Right-click "+gameObject.name);
	}
}

I think adding the Event Trigger component to the UI element is easier. Just follow these directions provided in this Answer by HarshadK:

  1. Add an Event Trigger component to your button game object.
  2. Click on Add New button and select PointerEnter.
  3. Now click on ‘+’ button to add a new item to the list of event of type PointerEnter(BaseEventData).
  4. Select the object containing your script.
  5. Now select the function to be called from the list of functions.

Attach your function to an EventTrigger script with EventType PointerClick. Inside the function:

if (Input.GetMouseButtonUp( 0 ))
{
  print( "left click" );
}
else if (Input.GetMouseButtonUp( 1 ))
{
  print( "right click" );
}
else if (Input.GetMouseButtonUp( 2 ))
{
  print( "middle click" );
}

Write the following code to the script and attach it to the button:

	public bool mouseEntered { get; set; }

	public void Update(){
		if(mouseEntered){
			if (Input.GetMouseButtonDown(1)) OnRightClick ();
		}
	}

Next, add the Event Trigger component to the button and set it up like in the picture:

40089-eventtrigger.jpg

Just use PointerEventData.pointerId on PC version.