Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to call a method when a bound property's value is changed from my editor?

Discussion in 'UI Toolkit' started by KristofferH, Jul 14, 2022.

  1. KristofferH

    KristofferH

    Joined:
    Oct 27, 2012
    Posts:
    51
    I have a slider and a field that both binds to the same field, so that I can drag the slider and at the same time see the coresponding value in the field, or so I can set a precis value using keyboard input.

    But I don't just want to change the value in a field, I want that value to update an object in the scene, e.g. set the intensity of a light.


    Code (CSharp):
    1. SerializedObject serializedController = new SerializedObject(controller);
    2.  
    3. SerializedProperty value = serializedController.FindProperty("_value");
    4.  
    5. Slider valueSlider = controllerRow.Q<Slider>("value-slider");
    6. FloatField valueField = controllerRow.Q<FloatField>("value-field");
    7.  
    8. valueSlider.BindProperty(value);
    9. valueField.BindProperty(value);
    The values are updated updated correctly in my editor window, and on the object itself in the Inspector, but ofcorse nothing happens with the light itself. I want to use the "value" as a percentage to multiply it with the max intensity of the light (stored in the controller) and then update the light source with the new intensity, something like this:

    Code (CSharp):
    1. public float _value = 0f;
    2. public float _maxIntensity = 1000f;
    3.  
    4. // Call this method everytime the _value field is changed.
    5. private void SetIntensity()
    6. {
    7.     if (light != null)
    8.         light.intensity = _maxIntensity * _value;
    9. }
    I tried binding to a property rather than a field, and added the method in the setter for it to be called, but Binding does not work for properties; serializedController.FindProperty("Value") becomes null.

    Code (CSharp):
    1. public float Value
    2. {
    3.     get { return _value; }
    4.     set
    5.     {
    6.         _value = value;
    7.         SetIntensity();
    8.     }
    9. }
    10.  
    11. private void SetIntensity()
    12. {
    13.     if (light != null)
    14.         light.intensity = _maxIntensity * _value;
    15. }
    So how can I call a method when a bound field is being changed?
     
  2. KristofferH

    KristofferH

    Joined:
    Oct 27, 2012
    Posts:
    51
  3. jonathanma_unity

    jonathanma_unity

    Unity Technologies

    Joined:
    Jan 7, 2019
    Posts:
    229
    Hi, you can try to register a value change callback on the fields with RegisterValueChangedCallback.

    Another approach is to use a PropertyField instead of the FloatField and then register for SerializedPropertyChangeEvent with RegisterValueChangeCallback.