Can I cache the SerializedProperty in custom PropertyDrawer.CreatePropertyGUI?

Can I cache the SerializedProperty as a member variable, which will be used in the UIElements event callback?

Hello, what UIElements event callback are you referring to? Can you give me a more concrete example of what you’re trying to achieve?

For example this code:

[CustomPropertyDrawer(typeof(TestObj))]
internal sealed class TestObjDrawer : PropertyDrawer
{
    private SerializedProperty boolValue;
    private SerializedProperty textValue;

    private PropertyField boolField;
    private PropertyField textField;

    public override VisualElement CreatePropertyGUI(
        SerializedProperty property)
    {
        this.intValue = property.FindPropertyRelative("boolValue");
        this.textValue = property.FindPropertyRelative("textValue");

        var asset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/TestObj.uxml");
        var root = asset.CloneTree();
        this.boolField = root.Q<PropertyField>("boolField");
        this.textField = root.Q<PropertyField>("textField");

        this.UpdateState();
        this.boolField.RegisterValueChangeCallback(e => this.UpdateState());

        return root;
    }

    private void UpdateState()
    {
        this.textField.SetEnable(this.boolValue.boolValue);
    }
}

Is it save to save the SerializedProperty and VisualElement as a member variable in a PropertyDrawer?

This should be fine. However, there is an easier way:

// ...
    this.boolField.RegisterValueChangeCallback(e => this.UpdateState(e.newValue));
        return root;
    }
    private void UpdateState(bool newBoolValue)
    {
        this.textField.SetEnable(newBoolValue);
    }
1 Like

So the ‘RegisterValueChangeCallback’ will invoke the event to initialize the state. I don’t need to invoke the UpdateState once again manually?

Hi, I think we can not store any widget or property as a member variable. One PropertyDrawer will reuse in multi-objects.