Hey !
I was wondering about the best solution to make a custom array/list field with a custom object selector.
For now i made a custom UIElement extending ListView. I then added a add button, displaying my custom selector. From my Add button, I have an object reference that I need to add to my array. Now I need to update my serializedproperty array with this new value, and propagate the change to my UIElement. How can I access the bound serialized array from inside my custom UIElement in order to modify it ?
Maybe I should explain my problem better !
I want to do a reusable UIElement which I can drag n drop using UI builder.
It’s basically a ListView with few more buttons so I decided to inherit from ListView because why not :
public class CustomListField : ListView
{
public new class UxmlFactory : UxmlFactory<CustomListField , UxmlTraits> { }
public CustomListField () : base(){
...
var btn_add = new Button();
btn_add.Add(new Label("Add ..."));
btn_add.RegisterCallback<ClickEvent>(OpenPopup);
hierarchy.Add(btn_add);
}
void OpenPopup(ClickEvent evt)
{
var e = (VisualElement)evt.currentTarget;
// This popup show a list of elements and returns the selected element using a callback
CustomDropdown.Open<CustomData>((VisualElement)evt.currentTarget, (data) => {
// Dont know how I'm supposed to update the array collection from here.
// I would like to be able to add/remove items
}, false,null);
}
}
I then use the bindingPath property in Uxml to bind it with my CustomData list
Here’s the result visually
(a custom dropdown open when clicking add button)
It works but I have no clue on how I’m supposed to modify the serialized array collection size from inside my class if I want to insert a new element. I’m really stuck in this one !
Still stuck infortunately ! Should I make a propertydrawer for my list instead ?
Hi,
With the Serialized Object bindings features you can automatically associate a ListView to an array property.
This example will walk you through it - the key part is the binding-path property in UXML (or bindingPath in C#):
For actually adding to the List, you’ll need to access the SerializedObject yourself. This example, specifically the
TexturePackEditor.OnClick method shows an example of this.
In general, I would advise keeping the logic in your custom editor or custom window and avoid using custom Visual Elements for such a use case. You can just make a composition of a ListView and a Button in a UXML file for example.
2 Likes