Skip to content

Instantly share code, notes, and snippets.

@pyjamads
Last active October 5, 2020 18:06
Show Gist options
  • Save pyjamads/27fbbd1e85f674acf3e6063f200049aa to your computer and use it in GitHub Desktop.
Save pyjamads/27fbbd1e85f674acf3e6063f200049aa to your computer and use it in GitHub Desktop.
Component Selector Dropdown Property Drawer, how the component property drawer should always have been displayed.
[CustomPropertyDrawer(typeof(Component))]
public class ComponentPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUILayout.BeginHorizontal();
var pos = new Rect(position);
pos.width = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
pos.x = position.x + position.width - pos.width;
position.width = position.width - pos.width;
EditorGUI.PropertyField(position, property);
var pressed = EditorGUI.DropdownButton(pos, GUIContent.none, FocusType.Keyboard);
if (pressed)
{
var menu = new GenericMenu();
menu.allowDuplicateNames = true;
var currentComp = (Component)property.objectReferenceValue;
if (currentComp == null)
{
menu.AddDisabledItem(new GUIContent("No Game Object Selected!"));
//Find all objects in the scene, and allow the user to select one from that!
var components = Object.FindObjectsOfType<GameObject>();
foreach (var component in components.OrderBy(item => item.name))
{
menu.AddItem(new GUIContent(component.name), false, () =>
{
property.objectReferenceValue = component;
property.serializedObject.ApplyModifiedProperties();
});
}
}
else
{
var components = currentComp.GetComponents<Component>();
var componentNames = components.Select((m) => m.GetType().Name)
.ToList();
for (var index = 0; index < components.Length; index++)
{
var name = componentNames[index];
var comp = components[index];
menu.AddItem(new GUIContent(name), false, () =>
{
property.objectReferenceValue = comp;
property.serializedObject.ApplyModifiedProperties();
});
}
}
menu.ShowAsContext();
}
EditorGUILayout.EndHorizontal();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment