Created
March 13, 2021 14:20
-
-
Save Angeart/689d9a8b4172d8413982b61e02119877 to your computer and use it in GitHub Desktop.
Unity - AutoAssignAttribute
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 UnityEngine; | |
| public class AutoAssignAttribute : PropertyAttribute | |
| { | |
| } |
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 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