Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll Rect manual scrolling through script Unity C#

I want to make a C# script for Unity to make the scroll view scroll up when I press "UP" key and scroll down when I press "DOWN" key.

like image 883
MBS Avatar asked Jan 29 '26 03:01

MBS


2 Answers

Simply use

ScrollRect.horizontalNormalizedPosition // value range (0 to 1)

or

ScrollRect.verticalNormalizedPosition // value range (0 to 1)

try to lerp these values accordingly on button click event handlers for up and down buttons.

Or you can have a look at scripts HorizontalScrollSnap.cs and VerticalScrollSnap.cs at UnityUI-Extentions

like image 182
Umair M Avatar answered Jan 31 '26 16:01

Umair M


The other answers seemed incomplete or overly complex, so here's how I did it. Assuming scroll is the direction you want to scroll, speed is a property that controls your scroll speed in content units/sec, and scrollRect is a reference to the ScrollRect component:

        if (scroll != 0) {
            float contentHeight = scrollRect.content.sizeDelta.y;
            float contentShift = speed * scroll * Time.deltaTime;
            scrollRect.verticalNormalizedPosition += contentShift / contentHeight;
        }

This should shift the right amount for any content size, and correctly causes the elastic rebound at the top and bottom (if your ScrollRect is configured for that).

like image 35
Joe Strout Avatar answered Jan 31 '26 17:01

Joe Strout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!