- Home /
UI Button: Detecting right mouse button
I currently use a script that claims to emulate the normal UI Button's Onclick functionality, but only detects right mouse button clicks. I can add Listeners to it as usual and it does indeed only detect RMB clicks. Problem is, it for some reason always calls ALL Listeners on ALL the Right Button Event scripts in the scene.
So my question is (since there seem to be several solutions by users, but no official ones): How can I make UI buttons detect RMB clicks like the UI Button class does with all MB clicks (meaning the options to call functions with a parameter)?
Here is the script I use currently, by the way.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using System.Collections;
[ExecuteInEditMode]
[AddComponentMenu("Event/RightButtonEvent")]
public class RightButtonEvent : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
[System.Serializable]public class RightButton : UnityEvent{}
public RightButton onRightDown;
public RightButton onRightUp;
private bool isOver = false;
void Start () {
}
void Update () {
if (Input.GetMouseButtonDown(1)) {
onRightDown.Invoke();
}
if (Input.GetMouseButtonUp(1)) {
onRightUp.Invoke();
}
}
public void OnPointerEnter(PointerEventData eventData) {
isOver = true;
}
public void OnPointerExit(PointerEventData eventData) {
isOver = false;
}
}
And for testing purposes, I added a Listener via script that calls a function:
public RightButtonEvent rightButtonEvent;
void Start() {
rightButtonEvent.onRightDown.AddListener(delegate { Test(); });
}
public void Test() {
Debug.Log("blubb");
}
Which, as described above, call ALL RightButtonEvent listeners in the scene.
Answer by Cherno · Jul 03, 2015 at 11:31 PM
BoredMoron thankfully answered this question on the forums, I'll just post his script here:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
public class RightClick : MonoBehaviour, IPointerClickHandler {
public UnityEvent leftClick;
public UnityEvent middleClick;
public UnityEvent rightClick;
public void OnPointerClick(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
leftClick.Invoke ();
else if (eventData.button == PointerEventData.InputButton.Middle)
middleClick.Invoke ();
else if (eventData.button == PointerEventData.InputButton.Right)
rightClick.Invoke ();
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613201349im_/https://answers.unity.com/themes/thub/images/avi.jpg)