Last active
May 29, 2020 20:55
-
-
Save Lazersquid/1b5344202a5de397c779d64523d1b327 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Sirenix.OdinInspector; | |
using Sirenix.OdinInspector.Editor; | |
using Sirenix.Utilities; | |
using UnityEngine; | |
public class ExampleBehaviour : MonoBehaviour | |
{ | |
[TypeSelector] | |
public int myField; | |
[TypeSelector(typeof(Collider))] | |
public int myOtherField; | |
} | |
public class TypeSelectorAttribute : Attribute | |
{ | |
public readonly Type BaseType; | |
public TypeSelectorAttribute(Type baseType = null) | |
{ | |
BaseType = baseType; | |
} | |
} | |
public class TypeSelectorAttributeDrawer : OdinAttributeDrawer<TypeSelectorAttribute> | |
{ | |
private static Dictionary<Type, string> customTypeNameDict = new Dictionary<Type, string>() | |
{ | |
{typeof(CapsuleCollider), "My Custom Name"}, | |
{typeof(BoxCollider), "I don't know"}, | |
}; | |
private ValueDropdownItem<Type>[] _validTypes; | |
protected override void Initialize() | |
{ | |
if (_validTypes != null) return; | |
var validTypes = AssemblyUtilities.GetTypes(AssemblyTypeFlags.All) | |
.Where(x => !x.IsAbstract) | |
.Where(x => !x.IsGenericType); | |
if (Attribute.BaseType != null) | |
{ | |
validTypes = validTypes.Where(x => Attribute.BaseType.IsAssignableFrom(x)); | |
} | |
_validTypes = validTypes | |
.Select( x => customTypeNameDict.TryGetValue(x, out var customName) | |
? new ValueDropdownItem<Type>(customName, x) | |
: new ValueDropdownItem<Type>(x.FullName.Replace('.', '/'), x)) | |
.ToArray(); | |
} | |
protected override void DrawPropertyLayout( GUIContent label ) | |
{ | |
IEnumerable<ValueDropdownItem<Type>> results = OdinSelector<ValueDropdownItem<Type>>.DrawSelectorDropdown( GUIContent.none, "Select a type..", DoSelector ); | |
if ( results != null ) | |
{ | |
var selectedType = results.FirstOrDefault().Value; | |
if (selectedType != null) | |
{ | |
Debug.Log($"Selected type: {selectedType}"); // use selected type here | |
} | |
} | |
GUILayout.Space( 2 ); | |
CallNextDrawer( label ); | |
} | |
protected OdinSelector<ValueDropdownItem<Type>> DoSelector( Rect buttonRect ) | |
{ | |
GenericSelector<ValueDropdownItem<Type>> selector = new GenericSelector<ValueDropdownItem<Type>>( _validTypes ); | |
selector.ShowInPopup( buttonRect ); | |
return selector; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment