Search Unity

SerializedObject changed event

Discussion in 'UIElements' started by cecarlsen, Jun 28, 2019.

  1. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    517
    I have a custom visual element (extending VisualElement) that has a ScriptableObject (EDIT: MonoBehaviour) ossociated with it. I would like to receive an event when a specific SerializedProperty of type List<GameObject> in the ScriptableObject (EDIT: MonoBehaviour) changes. However I would also be happy just to get a callback when any of the fields in the object changes.

    I have read the section about binding, but I'm not sure this that is what I need. The binding system has a ChangeEvent but it seems only to available for build-in elements that either derives from BindableElement or implements the IBindable interface. I do not wish to display the list, it represents connections between objects in a node system and is not meant to be displayed with standard UI.

    Any hints are appreciated.
     
    Last edited: Jul 25, 2019
  2. patrickf

    patrickf

    Unity Technologies

    Joined:
    Oct 24, 2016
    Posts:
    43
    Hi!
    Your ScriptableObject could detect if its properties have changed and do

    Code (CSharp):
    1. using (var changeEvent = ChangeEvent<YourPropertyValueType>.GetPooled(oldValue, newValue))
    2. {
    3.     changeEvent.target = yourVisualElement;
    4.     yourVisualElement.SendEvent(changeEvent);
    5. }
     
    Last edited: Jul 26, 2019
  3. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    517
    Thanks @patrickf

    Aha, that's how you fire events. Strange how you call Send on the element you want to send to.

    I don't want the ScriptableObject (actually it's a MonoBehaviour, but same deal) living in the scene to know anything about UIElements living in the Editor. If there is no way for UIElements to ask for change events on SerializedObjects, then I will resort to setting some sort of change counter on the object and check it from UIElements. But that just does not seem so smooth.
     
  4. patrickf

    patrickf

    Unity Technologies

    Joined:
    Oct 24, 2016
    Posts:
    43
    You don't need to sent the event to the target, but to an element in the panel. However, since the target is usually available, it usually ends up like this.

    If you don't want the MonoBehaviour to know about UIElements, you'll have to do as you wrote: make UIElements refresh itself based on the data/change list.
     
    cecarlsen likes this.