我确定问题已经存在,但我找不到,抱歉。
我正在尝试将对象的序列化字段与其其他组件同步。
假设我有一个字段“大小”,它会影响对象变换比例:
[SerializeField]
int _size;
我正在寻找事件处理程序或允许我执行的操作:
void onSerializedPropertyChange() {
transform.localScale = new Vector3(_size,_size,_size);
}
是否存在这样的方法?
最终的想法是使用多个属性并在预览结果时调整对象属性。
最佳答案
Update object based on serialized field?
您可以在添加 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, label);
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
关于c# - unity - 如何在序列化字段更改时更新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63778384/