simple drop down menu script for gui

Here is an example of a dropdown select country script:

    private Vector2 scrollViewVector = Vector2.zero;
    private string[] countrys = {"Any country","Afghanistan", "Albania", "Algeria"};//add the rest 
    int n,i,wichcountry;

    void Start () {
     n=0;i=0;wichcountry=0;
    }

    void OnGUI () {

     if(GUI.Button(new Rect(125,50,25,25), "")){
      if(n==0)n=1;
      else n=0;			
     }

     if(n==1){
       scrollViewVector = GUI.BeginScrollView (new Rect (25, 50, 100, 115), scrollViewVector, new Rect (0, 0, 300, 500));
       GUI.Box(new Rect(0,0,300,500), "");	
       for(i=0;i<4;i++){
        if(GUI.Button(new Rect(0,i*25,300,25), "")){
         n=0;wichcountry=i;			
        }			 	
        GUI.Label(new Rect(5,i*25,300,25), countrys[i]);			
       }
       GUI.EndScrollView();			
      }else{
       GUI.Label(new Rect(30,50,300,25), countrys[wichcountry]);
      }				
    }

make sure you make no buttons behind scroll view rectangle.

1 Like

Thanks this helped me a lot. I made some changes to make it more dynamic, such as, the scroll bars won’t pop up unless the number of items exceeds the default size, and you can move it by changing a Vector2.

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
	private Vector2 scrollViewVector = Vector2.zero;
	public Rect dropDownRect = new Rect(125,50,125,300); 
	public static string[] list = {"Drop_Down_Menu"};
	
	int indexNumber;
	bool show = false;

	void OnGUI()
	{	
		if(GUI.Button(new Rect((dropDownRect.x - 100), dropDownRect.y, dropDownRect.width, 25), ""))
		{
			if(!show)
			{
				show = true;
			}
			else
			{
				show = false;
			}
		}
		
		if(show)
		{
			scrollViewVector = GUI.BeginScrollView(new Rect((dropDownRect.x - 100), (dropDownRect.y + 25), dropDownRect.width, dropDownRect.height),scrollViewVector,new Rect(0, 0, dropDownRect.width, Mathf.Max(dropDownRect.height, (list.Length*25))));
			
			GUI.Box(new Rect(0, 0, dropDownRect.width, Mathf.Max(dropDownRect.height, (list.Length*25))), "");
			
			for(int index = 0; index < list.Length; index++)
			{
				
				if(GUI.Button(new Rect(0, (index*25), dropDownRect.height, 25), ""))
				{
					show = false;
					indexNumber = index;
				}
				
				GUI.Label(new Rect(5, (index*25), dropDownRect.height, 25), list[index]);
				
			}
			
			GUI.EndScrollView();	
		}
		else
		{
			GUI.Label(new Rect((dropDownRect.x - 95), dropDownRect.y, 300, 25), list[indexNumber]);
		}
		
	}
1 Like

Much better.
Everyone - use this in your script instead :slight_smile:
Also, don`t forget NOT to put any buttons behind scrollview rectangle.

And that is because of the… scrollview bug. :slight_smile:

sorry but what should i put ? i have inputField i want the date to show on
should i only but a button or inputField