SerializedPropertyHelper.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Linq.Expressions;
  3. using UnityEditor;
  4. namespace Cinemachine.Editor
  5. {
  6. /// <summary>
  7. /// Helpers for the editor
  8. /// </summary>
  9. public static class SerializedPropertyHelper
  10. {
  11. /// This is a way to get a field name string in such a manner that the compiler will
  12. /// generate errors for invalid fields. Much better than directly using strings.
  13. /// Usage: instead of
  14. /// <example>
  15. /// "m_MyField";
  16. /// </example>
  17. /// do this:
  18. /// <example>
  19. /// MyClass myclass = null;
  20. /// SerializedPropertyHelper.PropertyName( () => myClass.m_MyField);
  21. /// </example>
  22. public static string PropertyName(Expression<Func<object>> exp)
  23. {
  24. var body = exp.Body as MemberExpression;
  25. if (body == null)
  26. {
  27. var ubody = (UnaryExpression)exp.Body;
  28. body = ubody.Operand as MemberExpression;
  29. }
  30. return body.Member.Name;
  31. }
  32. /// Usage: instead of
  33. /// <example>
  34. /// mySerializedObject.FindProperty("m_MyField");
  35. /// </example>
  36. /// do this:
  37. /// <example>
  38. /// MyClass myclass = null;
  39. /// mySerializedObject.FindProperty( () => myClass.m_MyField);
  40. /// </example>
  41. public static SerializedProperty FindProperty(this SerializedObject obj, Expression<Func<object>> exp)
  42. {
  43. return obj.FindProperty(PropertyName(exp));
  44. }
  45. /// Usage: instead of
  46. /// <example>
  47. /// mySerializedProperty.FindPropertyRelative("m_MyField");
  48. /// </example>
  49. /// do this:
  50. /// <example>
  51. /// MyClass myclass = null;
  52. /// mySerializedProperty.FindPropertyRelative( () => myClass.m_MyField);
  53. /// </example>
  54. public static SerializedProperty FindPropertyRelative(this SerializedProperty obj, Expression<Func<object>> exp)
  55. {
  56. return obj.FindPropertyRelative(PropertyName(exp));
  57. }
  58. /// <summary>Get the value of a proprty, as an object</summary>
  59. public static object GetPropertyValue(SerializedProperty property)
  60. {
  61. var targetObject = property.serializedObject.targetObject;
  62. var targetObjectClassType = targetObject.GetType();
  63. var field = targetObjectClassType.GetField(property.propertyPath);
  64. if (field != null)
  65. return field.GetValue(targetObject);
  66. return null;
  67. }
  68. }
  69. }