Tanoda
OnEditorChange.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using System;
10using System.Reflection;
11#if UNITY_EDITOR
12using UnityEditor;
13#endif
14using UnityEngine;
15using UnityObject = UnityEngine.Object;
16
17namespace Leap.Unity.Attributes {
18
29 public readonly string methodName;
30
32 this.methodName = methodName;
33 }
34
35#if UNITY_EDITOR
36 private Action<UnityObject, object> _cachedDelegate;
37
38 public override void OnPropertyChanged(SerializedProperty property) {
39 base.OnPropertyChanged(property);
40
41 if (_cachedDelegate == null) {
42 Type type = targets[0].GetType();
43
44 PropertyInfo propertyInfo = type.GetProperty(methodName,
45 BindingFlags.Public |
46 BindingFlags.NonPublic |
47 BindingFlags.Instance
48 );
49 if (propertyInfo != null) {
50 _cachedDelegate = (obj, arg) => propertyInfo.SetValue(obj, arg, null);
51 }
52 else {
53 MethodInfo method = type.GetMethod(methodName,
54 BindingFlags.Public |
55 BindingFlags.NonPublic |
56 BindingFlags.Static |
57 BindingFlags.Instance |
58 BindingFlags.FlattenHierarchy
59 );
60
61 if (method == null) {
62 Debug.LogWarning("Could not find a property or method of the name " +
63 methodName + " " + "to invoke for the OnChange attribute.");
64 return;
65 }
66
67 int paramCount = method.GetParameters().Length;
68 if (paramCount == 0) {
69 _cachedDelegate = (obj, arg) => method.Invoke(obj, null);
70 } else if (paramCount == 1) {
71 object[] argArray = new object[1];
72 _cachedDelegate = (obj, arg) => {
73 argArray[0] = arg;
74 method.Invoke(obj, argArray);
75 };
76 } else {
77 Debug.LogWarning("Could not invoke the method " + methodName +
78 " from OnChange because the method had more than 1 argument.");
79 }
80 }
81 }
82
83 property.serializedObject.ApplyModifiedProperties();
84
85 foreach (var target in targets) {
86 object newValue = fieldInfo.GetValue(target);
87 _cachedDelegate(target, newValue);
88 }
89 }
90#endif
91 }
92}
UnityEngine.Object UnityObject
UnityEngine.Debug Debug
Definition: TanodaServer.cs:19
Use the OnChange attribute to recieve a callback whenever a field is changed. The callback can be in ...