Controlling the scrollbar with the mouse wheel

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.

How to do it...

To control the scrollbar with the mouse wheel, please follow these steps:

  1. Attach the following C# script class to the Main Camera:
    // 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;
            }
        }
    }    
  2. Test your scene. You should now be able to control the scrollbar with the mouse wheel.
    How to do it...

How it works...

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.

There's more...

In this recipe, the scrollbar height is determined by the application screen's height. However, there's no reason you couldn't add more variables to manually set its size and position.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.157.6