How to use the Scroll view UI element in Unity?

Ouzani Abd Raouf
3 min readJun 10, 2020

--

A Scroll view is a Unity UI element that contains a Scroll Rect, a mask and scrollbar components. It can be used when content that takes up a lot of space needs to be displayed in a small area. The Scroll Rect provides functionality to scroll over this content. The Mask ensures that only the scrollable content inside the Scroll Rect is visible. The Scroll view can also be combined with one or two Scrollbars that can be dragged to scroll horizontally or vertically.

Inserting a Scroll view

The important elements in a scroll view are the viewport, the scrolling content, and optionally one or two scrollbars.

The root gameObject named “Scroll view” has the “Scroll Rect” component attached to it.

The “Mask” component is attached to the viewport gameObject. The viewport Rect Transform needs to be referenced in the Viewport property of the Scroll Rect.

The “Content” gameObject which will contain all the scrolling content is a child of the Viewport and like its parent it needs to be referenced in the Content property of the Scroll Rect.

The scrollbars are optional. They are children to the root gameObject (Scroll View).

As mentioned above, we add our items to the “content” child gameObject. By default, the size of this gameObject is larger than the body of the scroll view but we can change its size and position in the Editor as needed. This works perfectly for static content, but if, for example, we want to add content items at run-time then the content area will not adjust the size accordingly and items which are not inside that area will not be displayed.

To dynamically change the size of the scroll view, follow the next steps:

  • Add a “Vertical layout group” component to the content gameObject. It will automatically adjust the position of items inside the content object.
  • Add a “Content size fitter” component to the same gameObject. Select the Horizontal and Vertical Fit drop downs to “Preferred size”.

Now, at run-time, try to add some items inside the content gameObject to test the Scroll View (for example by duplicating a button with the Ctrl+D keyboard shortcut).

--

--