Skip to content

Instantly share code, notes, and snippets.

@CoffeeVampir3
Last active April 4, 2021 06:11
Show Gist options
  • Save CoffeeVampir3/ebe2659589e071ca77ee7237af679943 to your computer and use it in GitHub Desktop.
Save CoffeeVampir3/ebe2659589e071ca77ee7237af679943 to your computer and use it in GitHub Desktop.
Serializable Type
[Serializable]
public class SerializedType : ISerializationCallbackReceiver
{
[SerializeField]
public string serializedTypeName = "";
[NonSerialized]
public Type type = null;
public SerializedType(System.Type t)
{
type = t;
}
public void OnBeforeSerialize()
{
if (type != null)
{
serializedTypeName = type.AssemblyQualifiedName;
}
}
public void OnAfterDeserialize()
{
type = Type.GetType(serializedTypeName);
}
}
[TypeSelect(typeof(Component))]
public SerializedType componentType;
[AttributeUsage(AttributeTargets.Field)]
public class TypeSelect : PropertyAttribute
{
public readonly Type selectTypesOf;
public TypeSelect(Type t)
{
selectTypesOf = t;
}
}
[CustomPropertyDrawer(typeof(TypeSelect))]
public class SpecialTypeDrawer : PropertyDrawer
{
private SerializedProperty typeField;
private DropdownField dropdown;
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
VisualElement ve = new VisualElement();
typeField = property.FindPropertyRelative(nameof(SerializedType.serializedTypeName));
if (typeField == null)
return null;
var typeSelectAttr = this.attribute as TypeSelect;
var types = TypeCache.GetTypesDerivedFrom(typeSelectAttr.selectTypesOf);
if(typeField == null)
Debug.Log("Null!");
List<string> things = new List<string>(types.Count);
foreach (var type in types)
{
things.Add(type.Name);
}
dropdown = new DropdownField(ObjectNames.NicifyVariableName(fieldInfo.Name),
things, 1);
dropdown.SetValueWithoutNotify(typeField.stringValue);
ve.Add(dropdown);
return ve;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment