using System.Collections.Generic; using UnityEngine; using UnityEditor; using YKMoon; namespace YKMoonEditor { [CustomPropertyDrawer(typeof(MonoBehaviourProperty))] public class PDrawer_MonoBehaviourProperty : PropertyDrawer { Vector2Int contentSize = new Vector2Int(2, 2);//2x2 Vector2 contentSpace = new Vector2(4, 2); Vector2 padding = new Vector2(4, 1); float rowHeight = 18f; public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return contentSize.y * (rowHeight + contentSpace.y) + padding.y * 2; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); //properties var p_go = property.FindPropertyRelative("go"); var p_mono = property.FindPropertyRelative("monoBehaviour"); var contentRect = new Rect(position.x, position.y, position.width, position.height); int index = 0; //MonoBehaviour using(new EditorGUI.DisabledScope(true)) { var rect = UEditorUtility.SplitRect(contentRect, contentSize, contentSpace, index++, padding); EditorGUI.PropertyField(new Rect(contentRect.x, contentRect.y, contentRect.width, rect.height), p_mono, GUIContent.none); index++; } //gameobject { var rect = UEditorUtility.SplitRect(contentRect, contentSize, contentSpace, index++, padding); EditorGUI.PropertyField(rect, p_go, GUIContent.none); } //MonoBehaviour selection { var rect = UEditorUtility.SplitRect(contentRect, contentSize, contentSpace, index++, padding); var newValue = DrawMonoBehaviourSelectPopup(p_go.objectReferenceValue as GameObject, rect, p_mono.objectReferenceValue as MonoBehaviour); if(newValue != p_mono.objectReferenceValue) { p_mono.objectReferenceValue = newValue; } } EditorGUI.EndProperty(); } #region Tool /// /// Ãè»æMonoBehaviourµ¯³ö¿ò /// private MonoBehaviour DrawMonoBehaviourSelectPopup(GameObject go, Rect rect, MonoBehaviour selectedType) { var monos = GetMonoBehaviours(go); var monoStrings = GetMonoBehaviourString(monos); int index = monos.IndexOf(selectedType); index = EditorGUI.Popup(rect, index, monoStrings.ToArray()); if(index >= 0) { return monos[index]; } else { return go == null ? null : monos[0]; } } private List GetMonoBehaviourString(List componnents) { List result = new List(); for(int i = 0; i < componnents.Count; i++) { if(componnents[i] == null) { result.Add("Null"); } else { result.Add(componnents[i].GetType().ToString()); } } return result; } private List GetMonoBehaviours(GameObject obj) { List monos = new List(); if(obj != null) { var components = ListPool.Get(); obj.GetComponents(typeof(MonoBehaviour), components); foreach(var comp in components) { if (comp is MonoBehaviour) { monos.Add(comp as MonoBehaviour); } } ListPool.Release(components); } //componnents.Insert(0, null); return monos; } #endregion } }