ScrollView : foreach makes scrollview not scrollable

Hi,

I have a scroll view and I want to add a button for each variable stored in a List<>, but apparently it makes it not scrollable.

int top = 5; bool isFirst = true;
GUI.BeginScrollView(....);
foreach (Item item in ListOfItems)
{
    if (GUI.Button(new Rect(5, top, ....)))
        DoSomething();

    // Just to create proper spacing between buttons
    if (isFirst)
        top += 32;
    else
        top += 37;
    isFirst = false;
}
GUI.EndScrollView();

How can I fix it ?

You have to use BeginScrollView to assign the scroll position like this:

Vector2 scrollPosition = Vector2.zero;
void OnGUI()
{
    int top = 5; bool isFirst = true;
    scrollPosition = GUI.BeginScrollView(position, scrollPosition, viewRect);
    foreach (Item item in ListOfItems)
    {
        if (GUI.Button(new Rect(5, top, ....)))
            DoSomething();
        if (isFirst)
            top += 32;
        else
            top += 37;
        isFirst = false;
    }
    GUI.EndScrollView();
}