Putting dictionary items in GUI ScrollView

I want to get items from my dictionary and put them in a scrollable box. The code I have below works fine so far. How do I access the objects related to each field in the scroll box? Is there a better method to do this with dictionaries?

public class Menu : MonoBehaviour {
	
	public GameObject player;
	public Vector2 position;
	public Vector2 size;
	private Vector2 OriginalPosition;
	public Vector2 scrollPosition = Vector2.zero;
	
	// Use this for initialization
	void Start () { 
		player.GetComponent<PlayerStatus>();
		OriginalPosition = position;
		
	
	}
	

	void OnGUI()
	{
		position = OriginalPosition;
		
		
		scrollPosition = GUI.BeginScrollView(new Rect(10, 300, 100, 100), scrollPosition, new Rect(0, 0, 220, 200));
		foreach(KeyValuePair<Items,int> pair in Inventory.Potions){
		position.y += 30;	
        GUI.Box(new Rect(0, position.y, 100, 20), pair.Key.itemName + " : " + pair.Value);
		}
        GUI.EndScrollView();
	
	}
}

It seems you have trouble to wrap your head around the immediate GUI system in Unity :wink:

Your code in OnGUI does not “create” a GUI, it just “displays” it. OnGUI is called every frame like Update. Well it’s actually called multiple times per frame to process other events. The Event class is strongly connected to OnGUI. All the GUI function use the event class to determine the current event and perform the proper action.

Are you sure your item class is called “Items”? I used “Item” in my example below.

Here’s an example:

void OnGUI()
{
    GUILayout.BeginArea(new Rect(10, 300, 100, 100));
    scrollPosition = GUILayout.BeginScrollView(scrollPosition);
    foreach(KeyValuePair<Item,int> pair in Potions)
    {
        GUILayout.BeginHorizontal("box", GUILayout.Height(20)); // style the group like a box
          GUILayout.Label(pair.Key.itemName + " : " + pair.Value);
          if (pair.Value > 0)
          {
              if (GUILayout.Button("Reduce", GUILayout.Width(70)))
              {
                  Potions[pair.Key] = Potions[pair.Key] - 1;
              }
          }
        GUILayout.EndHorizontal();
    }
    GUILayout.EndScrollView();
    GUILayout.EndArea();
}

This will display a button behind each item in the list. When you press the button, it will decrement the count of that element.