How to persist UI-specific state with viewDataKey?

Hi,

I’m trying to use the viewDataKey field of VisualElement to persist some UI-specific state (an element’s position) across domain reloads.

I have a custom visual element instantiated in UXML, defined as below. The element has a pan manipulator (which moves the element). My visual element subclass updates a local ‘position’ field each time a pan is completed, which is what I’m hoping will get serialized/persisted. I can then initialize the element to this serialized position field to maintain its position across domain reloads.

public class MyContentView : VisualElement
{
    private const string ViewDataKey = "3dbca16b-29fd-4ba8-97af-68f47265c2a1";

    [SerializeField] private Vector2 position;

    public MyContentView()
    {
        var panManipulator = new PanManipulator(MouseButton.MiddleMouse);
        panManipulator.OnPannedToPosition += OnPannedToPosition;
        this.AddManipulator(panManipulator);

        this.viewDataKey = ViewDataKey;
    }

    private void OnPannedToPosition(Vector2 position, PanManipulator.PanState state)
    {
        if (state == PanManipulator.PanState.Ended)
        {
            this.position = position;
        }
    }

    public class Factory : UxmlFactory<MyContentView> { }
}

However, the position field of MyContentView is always Vector2.zero after a domain reload. The documentation states that:

…so I’m not entirely sure what else I need to configure here. Any help is much appreciated.

-andy.

(Unity Version: 2019.1.0b10)

Unfortunately, the view data API currently only works with some controls that come with UIE (hence the comment on “element that supports it”). It is not extensible at this time. The APIs to enable view data persistence on your own custom controls is internal.

1 Like

Thanks a lot for your quick reply @uDamian . Ahh I see, thank you for the info. For now then I will store my UI-specific data on the EditorWindow itself (so it gets serialized) and pass a reference to this data store to the VisualElements that require it.

Are there any plans to support custom controls that have state?

The lack of public access to the APIs I mention above makes it not possible to add persistence support for your custom APIs. We will make them public eventually.