c# - Unity C#,脚本如何知道公共(public)变量(不是属性)何时更改

标签 c# unity3d getter-setter

例如UnityEngine.UI.Text

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

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

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

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

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

This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only). https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnValidate.html

最佳答案

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

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

例子:

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++;
    }
}

关于c# - Unity C#,脚本如何知道公共(public)变量(不是属性)何时更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37958136/

相关文章:

c# - 将 CookiesContainer 对象从 WCF 服务返回给客户端

c# - 将 xml 存储在已编译的 DLL 中

c# - 3D 体素网格视线 Bresenham 算法

javascript - 模仿 Javascript 中的私有(private)变量

java - 将枚举视为类中的常规属性

java - 某些验证方法遇到问题

C# - SSH Winforms 模拟控制台

c# - 即使设置为非持久性,ASP.NET MVC 4 身份验证 cookie 也会被保存

c# - 如何在 C# 中创建选择加入方法继承?

c# - 玩家在与标记对象碰撞时消失