- Home /
How can i create a pup-up menu like the one for choose the shader on materials in unity 2019?
Hi guys, I'm working on an ediotr tool, and I need to create the pop-up menu like the one in the material inspector. Look the image to understand what I mean: https://ibb.co/fFHVvd8 I searched a lot on Internet, but i couldn't find nothing. I also tried to check the Unity source code on GitHub, but nothing. I hope you can help me.
Thank you in advance!
Answer by nratcliff · Jun 29, 2019 at 12:55 AM
It took some digging, but I found the shader dropdown implementation in the source reference here. Using that, I put together a quick custom editor that has its own AdvancedDropdown as an example:
using System;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
[CustomEditor(typeof(ScriptWithDropdown))]
public class EditorWithDropdown : Editor
{
private string selectedItemName = null; // the currently selected item
private AdvancedDropdownState dropdownState = null; // the stored state of the dropdown
public override void OnInspectorGUI()
{
Rect position = EditorGUILayout.GetControlRect();
// set the dropdown label
var label = new GUIContent("Custom Dropdown");
if(selectedItemName != null)
{
label = new GUIContent(selectedItemName);
}
// draw the dropdown
if(EditorGUI.DropdownButton(position, label, FocusType.Keyboard))
{
var dropdown = new CustomAdvancedDropdown(
dropdownState, Dropdown_ItemSelected);
dropdown.Show(position);
}
base.OnInspectorGUI();
}
// called from CustomAdvancedDropdown when selection changes
private void Dropdown_ItemSelected(string item)
{
selectedItemName = item;
}
private class CustomAdvancedDropdown : AdvancedDropdown
{
private Action<string> onItemSelected;
public CustomAdvancedDropdown(AdvancedDropdownState state, Action<string> onItemSelected)
: base(state)
{
minimumSize = new Vector2(270, 308);
this.onItemSelected = onItemSelected; // add item selected callback
}
// builds the dropdown menu
protected override AdvancedDropdownItem BuildRoot()
{
// create the root element
AdvancedDropdownItem root = new AdvancedDropdownItem("Root Name");
// add basic child elements
root.AddChild(new AdvancedDropdownItem("Item 1"));
root.AddChild(new AdvancedDropdownItem("Item 2"));
root.AddChild(new AdvancedDropdownItem("Item 3"));
root.AddChild(new AdvancedDropdownItem("Item 4"));
root.AddChild(new AdvancedDropdownItem("Item 5"));
root.AddChild(new AdvancedDropdownItem("etc."));
return root;
}
// called when an item is selected
protected override void ItemSelected(AdvancedDropdownItem item)
{
// alert item selected
onItemSelected(item.name);
}
}
}
Hopefully this helps! I can't seem to find any documentation for AdvancedDropdown, but both of the source reference links I provided above give quite a bit of insight.
Good luck!