Unity C#,脚本如何知道公共变量(而不是属性)何时发生变化

b.b*_*ben 4 c# unity-game-engine getter-setter

例如UnityEngine.UI.Text

它包含text用于将文本值设置为字符串的变量。

现在,在我自己的类中,我使用 property(get;set) 而不是直接访问变量,这让我能够在设置新值时更新视图或触发一些事件。问题是当使用属性(获取设置)时,它不会在检查器甚至集成测试工具中显示该字段。

但Unity的文本组件决定不使用get set。在我看来,我对处理价值变化感到不舒服。

问题是原始UnityEngine.UI.Text变量text如何处理这个问题?

我认为这不仅仅是OnValidate()因为它只能在编辑器上工作。但text变量也适用于运行时脚本。

当加载脚本或在检查器中更改值时调用此函数(仅在编辑器中调用)。 https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnValidate.html

Ale*_*alm 5

如果您不使用单一行为(因此您可以执行 OnValidate())或想要进行轮询,那么您可以选择按照此要点使用 propertyattribute 字符串来方法反射解决方案。下面还有一个简单的实现和示例:

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
Run Code Online (Sandbox Code Playgroud)

例子:

using UnityEngine;

public class OnChangedCallTester : MonoBehaviour
{
    public bool UpdateProp = true;

    [SerializeField]
    [OnChangedCall("ImChanged")]
    private int myPropVar;

    public int MyProperty
    {
        get => myPropVar;
        set { myPropVar = value; ImChanged();  }
    }


    public void ImChanged() => Debug.Log("I have changed to" + myPropVar);

    private void Update()
    {
        if (UpdateProp)
            MyProperty++;
    }
}
Run Code Online (Sandbox Code Playgroud)