using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEditor; using UnityEditor.UIElements; using UnityEngine.UIElements; namespace RPGCoreCommon.DropTable.Editor { public class DropTableGroupElement : VisualElement { // Property data private SerializedProperty _property; private SerializedProperty _propertyRows; private List _rowElements = new(); // Elements private readonly EnumField _chanceTypeField; private readonly VisualElement _addRowButton; private readonly ListView _list; public DropTableGroupElement(SerializedProperty property) : this() { BindProperty(property); } public DropTableGroupElement() { DropTableDrawer.groupVisualTreeAsset.CloneTree(this); SetEnabled(false); // CHANCE TYPE _chanceTypeField = this.Q("dt-chance-type"); _chanceTypeField.RegisterValueChangedCallback(_ => Refresh()); // ADD (replacement for default list button) _addRowButton = this.Q("dt-add-row"); _addRowButton.RegisterCallback(_ => _list.onAdd(_list)); // LIST _list = this.Q("dt-list"); _list.makeItem = () => new DropTableGroupRowElement(); _list.bindItem = (element, i) => { var rowElement = element as DropTableGroupRowElement; _rowElements.Add(rowElement); rowElement.BindProperty(_propertyRows.GetArrayElementAtIndex(i)); }; _list.unbindItem = (element, _) => _rowElements.Remove(element as DropTableGroupRowElement); _list.onAdd = _ => { _propertyRows.arraySize++; _propertyRows.GetArrayElementAtIndex(_propertyRows.arraySize - 1).boxedValue = new DropTableGroupRow(); _propertyRows.serializedObject.ApplyModifiedProperties(); _list.RefreshItems(); }; } /// /// Created by . First in hierarchy . /// internal void BindProperty(SerializedProperty property) { _property = property; _propertyRows = _property.FindPropertyRelative(nameof(DropTableGroup.rows)); _chanceTypeField.BindProperty(_property.FindPropertyRelative(nameof(DropTableGroup.chanceType))); _list.BindProperty(_propertyRows); SetEnabled(true); } internal void Refresh() { var weightSum = (_property.boxedValue as DropTableGroup).rows.Sum(row => row.chance); _rowElements.ForEach(row => row.Refresh((ChanceTypeEnum)_chanceTypeField.value, weightSum)); } } }