Guest User

Untitled

a guest
Jul 19th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. using System.Linq;
  2. using UnityEngine;
  3. using UnityEditor;
  4. using System;
  5.  
  6. public class OnChangedCallAttribute : PropertyAttribute
  7. {
  8. public enum RunTimeCriteriaEnum
  9. {
  10. EditorOnly,
  11. PlayModeOnly,
  12. Both
  13. }
  14. public string methodName;
  15. public object[] arguments;
  16. public RunTimeCriteriaEnum Criteria = RunTimeCriteriaEnum.Both;
  17.  
  18. public OnChangedCallAttribute(string methodNameNoArguments, RunTimeCriteriaEnum runTimeCriteria = RunTimeCriteriaEnum.Both)
  19. {
  20. methodName = methodNameNoArguments;
  21. arguments = new object[0];
  22. Criteria = runTimeCriteria;
  23. }
  24.  
  25. public OnChangedCallAttribute(string methodNameNoArguments, object[] arguments, RunTimeCriteriaEnum runTimeCriteria = RunTimeCriteriaEnum.Both)
  26. {
  27. methodName = methodNameNoArguments;
  28. this.arguments = arguments;
  29. Criteria = runTimeCriteria;
  30. }
  31. }
  32.  
  33. #if UNITY_EDITOR
  34.  
  35. [CustomPropertyDrawer(typeof(OnChangedCallAttribute))]
  36. public class OnChangedCallAttributePropertyDrawer : PropertyDrawer
  37. {
  38. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  39. {
  40. EditorGUI.BeginChangeCheck();
  41. EditorGUI.PropertyField(position, property);
  42. if (EditorGUI.EndChangeCheck())
  43. {
  44. OnChangedCallAttribute at = attribute as OnChangedCallAttribute;
  45. //Exit if it is not in the right play mode
  46. if (at.Criteria != OnChangedCallAttribute.RunTimeCriteriaEnum.Both
  47. && ((!EditorApplication.isPlaying && at.Criteria == OnChangedCallAttribute.RunTimeCriteriaEnum.PlayModeOnly)
  48. || (EditorApplication.isPlaying && at.Criteria == OnChangedCallAttribute.RunTimeCriteriaEnum.EditorOnly)))
  49. return;
  50.  
  51. Type parentType = property.serializedObject.targetObject.GetType();
  52.  
  53. var findMethod = parentType.GetMethods().Where(m => m.Name == at.methodName).ToList();
  54. if(findMethod.Count() == 0) // Found?
  55. {
  56. Debug.LogError(string.Format("Error: [OnChangedCall(\"{0}\")] Method Name in ({1}) not found. Did you perhaps typo?", at.methodName, parentType.ToString()));
  57. return;
  58. }
  59.  
  60. var method = findMethod.First();
  61. if(method.GetParameters().Length != at.arguments.Length) // All arguments supplied?
  62. {
  63. Debug.LogError(string.Format("Error: [OnChangedCall] {0} in ({1}) Requires {2} arguments {3} supplied.", at.methodName, parentType.ToString(), method.GetParameters().Length, at.arguments.Length));
  64. return;
  65. }
  66.  
  67. method.Invoke(property.serializedObject.targetObject, at.arguments);
  68. }
  69. }
  70. }
  71.  
  72. #endif
Add Comment
Please, Sign In to add comment