尝试制作了一个监听任意Object属性的方片条.主要思路就是通过枚举该对象的属性,显示在inspector上.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
public class ProgressListener : MonoBehaviour{ [HideInInspector] public float progressListened; [HideInInspector] public string progressName ="unidentified"; public Object target; private Image _image; private bool _isTargetNotNull; private void Awake(){ _isTargetNotNull = target != null; _image = this.GetComponent<Image>(); }
private float GetValue(){ if (_isTargetNotNull){ Type targetType = target.GetType(); var propertyInfo = targetType.GetProperty(progressName); if (propertyInfo != null) return (float) propertyInfo.GetValue(target); } return 0; } void Update(){ progressListened = GetValue(); _image.fillAmount = progressListened; } }
|
and to make it accessible from inspector.we iterator the scriptobject’s member and give a popup list to user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
public class ProgressListenerDrawer : Editor{ private SerializedProperty _serializedTarget; public string[] targetFeatureNames;
private void GetFeatureNames(){ var serializedTargetValues= serializedObject.FindProperty("target").objectReferenceValue; var targetFeatureNamesList = new List<string>(); foreach (var variable in serializedTargetValues.GetType().GetProperties()){ if(variable.PropertyType==typeof(float)) targetFeatureNamesList.Add(variable.Name); } targetFeatureNames = targetFeatureNamesList.ToArray(); } void OnEnable(){ _serializedTarget = serializedObject.FindProperty("target"); GetFeatureNames(); var foundProperty= serializedObject.FindProperty("progressName"); index = Array.IndexOf(targetFeatureNames,foundProperty.stringValue); } private int index; public override void OnInspectorGUI(){ base.OnInspectorGUI(); index = EditorGUILayout.Popup( "Feature:", index, targetFeatureNames); var foundProperty= serializedObject.FindProperty("progressName"); foundProperty.stringValue = (targetFeatureNames[index]); foundProperty.serializedObject.ApplyModifiedProperties(); } }
|
很方便.
近期评论