For many users, there is nothing more natural than moving a scrollbar with the mouse wheel. However, this is not natively supported by Unity. In this recipe, we will add mouse wheel support to a vertical scrollbar.
To control the scrollbar with the mouse wheel, please follow these steps:
// file: ScrollWheel.cs using UnityEngine; using System.Collections; public class ScrollWheel : MonoBehaviour { public int margin; public bool allScreen = true; public float min = 0.0f; public float max = 10.0f; public float value = 10.0f; public float speed = 5; void OnGUI() { Rect rect = new Rect(margin, margin, 30, Screen.height - (margin * 2)); value = GUI.VerticalScrollbar(rect, value, 1.0f, max, min); bool onArea; if (!allScreen && !rect.Contains(Input.mousePosition)) { onArea = false; } else { onArea = true; } float vsMove = Input.GetAxis("Mouse ScrollWheel") * speed; if ((value + vsMove) > min && onArea) { value += vsMove; } } }
Since the scrollbar's handle position is given by a variable (in our case, vsBar)
, all we needed to do was increment that variable according to the mouse wheel input.
We have also added a few variables to enhance the scrollbar customization: margin, minimum and maximum values, scroll speed; and also a Boolean variable to enable/disable the mouse wheel input when the mouse cursor is not directly on top of the scrollbar.
52.15.56.12