Game Development Reference
In-Depth Information
In this code, we define a simple function (
addScrollViewListItem
) to draw a list
item (consisting of a label and checkbox). We then begin the
ScrollView
control by
passing the visible area (the first
Rect
parameter), the starting scroll position, and
finally the virtual area behind the control (the second
Rect
parameter). Then we
use that to draw 20 list items inside the virtual area of the
ScrollView
control
using our helper function before finishing off and closing the control with the
EndScrollView
command.
If you want to, you can also nest
ScrollView
controls within each other.
The
ScrollView
control also has some actions to control its use like the
ScrollTo
command. This command will move the visible area to the coordinates of the virtual
layer, bringing it into focus. (The coordinates for this are based on the top-left
position of the virtual layer; 0,0 being top-left.)
To use the
ScrollTo
function on
ScrollView
, you must use it within the
Begin
and
End
ScrollView
commands. For example, we can add a button in
ScrollView
to
jump to the top-left of the virtual area, for example:
public Vector2 scrollPosition = Vector2.zero;
void OnGUI()
{
scrollPosition = GUI.BeginScrollView(
new Rect(10, 10, 100, 50),
scrollPosition,
new Rect(0, 0, 220, 10));
if (GUI.Button(new Rect(120, 0, 100, 20), "Go to Top Left"))
GUI.ScrollTo(new Rect(0, 0, 100, 20));
GUI.EndScrollView();
}
You can also additionally turn on/off the sliders on either side of the control by
specifying the
BeginScrollView
statement using the
alwayShowHorizontal
and
alwayShowVertical
properties; these are highlighted here in an updated
GUI.BeginScrollView
call:
Vector2 scrollPosition = Vector2.zero;
bool ShowVertical = false; // turn off vertical scrollbar