ShineAndLearn
ShineAndLearn

Reputation: 31

How to enable ScrollView in this code?

    void OnGUI() {

    scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(400), GUILayout.Height(250));

        for (int i = 0; i < ItemList.Count; i++) {
        GUI.Label(new Rect(BoxTile.x, (BoxTile.height * i) + BoxTile.y + BoxTile.height, BoxTile.width, BoxTile.height), ItemList[i].Title, style );
        GUI.Label(new Rect(BoxDes.x, (BoxDes.height * i) + BoxDes.y + BoxDes.height, BoxDes.width, BoxDes.height), ItemList[i].Description, style );
        GUI.Label(new Rect(BoxCost.x, (BoxCost.height * i) + BoxCost.y + BoxCost.height, BoxCost.width, BoxCost.height), ItemList[i].Cost, style );
        if (GUI.Button(new Rect(BoxBtn.x, ((BoxBtn.height+15) * i)+ BoxBtn.y + BoxBtn.height+15, BoxBtn.width, BoxBtn.height), "x" )) {
            ItemList.RemoveAt(i);
        }
        }
    GUILayout.EndScrollView();
}

I am trying to create a list of item where it will just keep expanding, then I can use a scroll bar to scroll through the list of items in Unity Script vertically by using C#. However, it seemed like the scroll bar will just not appear on my list.

With my limited knowledge in Unity (4.6), I am not sure how to make modification on this codes to show the scrollbar, can someone please show me some light on this? Thanks in advance.

Upvotes: 0

Views: 833

Answers (2)

peroon
peroon

Reputation: 84

After Unity 4.6, OnGUI() is not recommended.

uGUI is easy to make and visible in Scene View.

Let's make uGUI Scroll View in 5 minutes! http://petlust.hateblo.jp/entry/2014/08/31/230134

Upvotes: 1

Venkat at Axiom Studios
Venkat at Axiom Studios

Reputation: 2516

BeginScrollView is an overloaded method. One of the overloads lets you specify when to show the scrollbars. The default behavior is to show the scroll bar only when needed (when the content "overflows" the display Rect)

The overload you want to use is

public static Vector2 BeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical);

Link to GUI.BeginScrollView on Unity's API Docs

Change your code to read as follows

scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(400), GUILayout.Height(250), true, true);

Upvotes: 1

Related Questions