Search Unity

Question Dynamic defaultValue in UxmlAttributeDescription

Discussion in 'UI Toolkit' started by _geo__, Jun 2, 2023.

  1. _geo__

    _geo__

    Joined:
    Feb 26, 2014
    Posts:
    1,336
    I have a custom component which I want to add a persistent guid to.
    That guid is generated anew for each new element. Yet, I am lacking a way to actually persist it into the xml.

    The code blow populates the field with a new guid. Yet it does so every time a new instance is created and it is not saved in the xml.
    Code (csharp):
    1. public new class UxmlTraits : VisualElement.UxmlTraits
    2. {
    3.    UxmlStringAttributeDescription _guid = new UxmlStringAttributeDescription { name = "Guid", defaultValue = System.Guid.NewGuid().ToString() };
    4. }
    upload_2023-6-2_18-45-3.png

    This seems logical to me. The default value should always be the same and therefore the UI Builder treats it as if it were.

    Now here is what I want. After the first initialization I want the guid to have a value set which is not the default and which is stored in the xml if the save button is pressed. It would look like this:

    upload_2023-6-2_18-36-24.png

    I do have a proof-of-concept solution which involves a lot of reflection. Basically I am filling the m_Properties list of the UXMLAsset after initialization. I am not even 100% sure this works in all cases. It's very nasty.

    Here comes my question:

    Is there a public API to SET the value of UXML properties?
    Like the inverse of what
    GetValueFromBag(bag, cc);
    does.

    Thank you.