基于序列化字段更新对象?
当您添加 OnChangedCall 元素时,您可以更新具有 SerializeField 的变量。
成员变量:
[SerializeField]
[OnChangedCall("onSerializedPropertyChange")]
private int _size;
您现在应该能够将函数作为字符串添加到括号中,并且应该在更改时调用它。
调用的方法必须是公开的,否则会产生错误!
方法:
public void onSerializedPropertyChange() {
transform.localScale = new Vector3(_size,_size,_size);
}
OnChangedCall 是一个自定义的 PropertyAttribute,需要从它继承。
OnChangedCall 类:
using System.Linq;
using UnityEngine;
using UnityEditor;
using System.Reflection;
public class OnChangedCallAttribute : PropertyAttribute
{
public string methodName;
public OnChangedCallAttribute(string methodNameNoArguments)
{
methodName = methodNameNoArguments;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(OnChangedCallAttribute))]
public class OnChangedCallAttributePropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(position, property);
if(EditorGUI.EndChangeCheck())
{
OnChangedCallAttribute at = attribute as OnChangedCallAttribute;
MethodInfo method = property.serializedObject.targetObject.GetType().GetMethods().Where(m => m.Name == at.methodName).First();
if (method != null && method.GetParameters().Count() == 0)// Only instantiate methods with 0 parameters
method.Invoke(property.serializedObject.targetObject, null);
}
}
}
#endif