Skip to content

Instantly share code, notes, and snippets.

@Angeart
Created March 13, 2021 14:20
Show Gist options
  • Select an option

  • Save Angeart/689d9a8b4172d8413982b61e02119877 to your computer and use it in GitHub Desktop.

Select an option

Save Angeart/689d9a8b4172d8413982b61e02119877 to your computer and use it in GitHub Desktop.
Unity - AutoAssignAttribute
using UnityEngine;
public class AutoAssignAttribute : PropertyAttribute
{
}
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(AutoAssignAttribute))]
public class AutoAssignPropertyDrawer: PropertyDrawer
{
private Type GetPropertyType(SerializedProperty property, bool isArrayListType = false)
{
var fieldInfo = property.GetFieldInfo();
// 配列の場合は配列のTypeを返す
if (isArrayListType && property.isArray && property.propertyType != SerializedPropertyType.String)
return fieldInfo.FieldType.IsArray
? fieldInfo.FieldType.GetElementType()
: fieldInfo.FieldType.GetGenericArguments()[0];
return fieldInfo.FieldType;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.PropertyField(position, property, label);
if (property.propertyType != SerializedPropertyType.ObjectReference)
return;
if (property.objectReferenceValue != null)
return;
var type = GetPropertyType(property);
if (!type.IsSubclassOf(typeof(Component)))
return;
var comp = property.serializedObject.targetObject as Component;
if (comp == null)
return;
var addc = comp.gameObject.GetComponent(type);
if (addc != null)
{
property.objectReferenceValue = addc;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment