c# - unity - 如何在序列化字段更改时更新对象?

标签 c# unity3d

我确定问题已经存在,但我找不到,抱歉。

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

假设我有一个字段“大小”,它会影响对象变换比例:

[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/

相关文章:

c# - 为什么我在执行 HTTP POST 时用完了流的字节数?

c# - 使用 Unity Video Player 连续无缝播放不同的视频

c# - 在这种情况下我可以使用 foreach 吗?如何写入行字符串 "cool"?

c# - Automapper DynamicMap 无法映射匿名类型列表

c# - Unity - 在游戏中添加背景音乐

c# - GameObject 不允许超过一个 child

c# - Unity不断获取: “Can not play a disabled audio source”

c# - 为 int、float 等类型分配额外的属性以进行反射

c# - 开发支持多个数据库的应用程序

c# - ListView 中具有相同文本/内容的项目的问题