- Home /
Change which mouse button is used to scroll in ScrollRect [SOLVED]
I've created a new ScrollView. How do I change which mouse button is used to scroll in ScrollRect. By default it's the left mouse button. I'd like to be able to change this to another mouse button. I'd also like to be able to use a keyboard key and disable it altogether (via script without disabling the scrollbars), but mainly I at least want to change it from the left mouse button.
Answer by nsfnotthrowingaway · Jun 29, 2016 at 05:44 PM
Solved with help I got here:
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class MiddleScrollRect : ScrollRect
{
public override void OnBeginDrag(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Middle)
{
eventData.button = PointerEventData.InputButton.Left;
base.OnBeginDrag(eventData);
}
}
public override void OnEndDrag(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Middle)
{
eventData.button = PointerEventData.InputButton.Left;
base.OnEndDrag(eventData);
}
}
public override void OnDrag(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Middle)
{
eventData.button = PointerEventData.InputButton.Left;
base.OnDrag(eventData);
}
}
}
Thanks! Tip for others: place this script INSTEAD of original ScrollRect.
Answer by ccoddes · Mar 05, 2017 at 03:37 PM
Hi, I used to face the same problem. This is an alternative solution I came up with, as I didn't want to convert the middle click pointer events to left clicks (as in the answer shared by @nsfnotthrowingaway):
The solution is rather simple:
Create a new class that overrides the default ScrollRect's OnDrag() event handler.
Move the content's localPosition, using eventData.delta to determine the distance to move.
Prevent the contents from moving out of the ScrollRect bounds by making use of the ScrollRect.normalizedPosition property, ensuring x and y dimensions stay between 0.0 and 1.0.
Sample code:
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class MiddleScrollRect : ScrollRect {
public override void OnDrag(PointerEventData eventData){
if (Input.GetMouseButton(2)) {
content.localPosition = content.localPosition + new Vector3(eventData.delta.x, eventData.delta.y);
normalizedPosition = new Vector2(Mathf.Clamp(normalizedPosition.x, 0.0f, 1.0f), Mathf.Clamp(normalizedPosition.y, 0.0f, 1.0f));
}
}
}
Hope this helps!
Your answer
![](https://koobas.hobune.stream/wayback/20220612083002im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Terminate drag while mouse is still down 0 Answers
Moving a ScrollRect child via script to focus on some point. 0 Answers
Scroll Rect only scrolling while mouse is inside rect 0 Answers
Scaling scroll view width to its content width or vice versa 0 Answers
Scrollview with dynamic header (disappear when scroll up and appear when scroll down... smoothly) 0 Answers