1

我确定问题已经存在,但我找不到它,对不起。

我正在尝试将对象的序列化字段与其其他组件同步。

假设我有一个应该影响对象变换比例的“大小”字段:

[SerializeField]
int _size;

我正在寻找一个事件处理程序或允许我做的事情:

void onSerializedPropertyChange() {
    transform.localScale = new Vector3(_size,_size,_size);
}

存在这样的方法吗?

最后的想法是使用多个属性并在预览结果的同时调整对象属性。

4

3 回答 3

4

基于序列化字段更新对象?

当您添加 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
于 2020-09-07T13:20:42.887 回答
0
 public class UIAnimatorGroup:MonoBehaviour
    {
        public UIAnimatorTransform _animatorTransform;

    }

[System.Serializable]
public class UIAnimatorTransform
{
    [HideInInspector] public Matrix4x4 LocalMatrix4X4; // 局部
    [HideInInspector] public Matrix4x4 GobleMatrix4X4;
    [HideInInspector] public UIAnimatorTransform parent;

    [SerializeField] 
    [OnChangedCall("onSerializedPropertyChange","UIAnimatorTransform")]
    private Vector3 position;

    [SerializeField] 
    [OnChangedCall("onSerializedPropertyChange","UIAnimatorTransform")]
    private Vector3 rotation;

    [SerializeField] 
    [OnChangedCall("onSerializedPropertyChange","UIAnimatorTransform")]
    private Vector3 scale;

    public void onSerializedPropertyChange()
    {
        SetLocalMatrixByTransform();
        CalculateGobleTransform();
    }
}
于 2021-12-05T16:33:22.980 回答
0

怎么样[ExecuteInEditMode]

然后就可以使用正常的Update()方法了。

于 2021-12-19T14:41:30.140 回答