Hi, I’ve been struggling with a bug in my code that i don’t understand. i have the following:
2 gameObjects, when i right click on a gameObject it will Display flex a VisualElement containing a ListView. This Listview is also populated with data like so:
public void InitializeInteractionMenu(VisualElement root, VisualTreeAsset interactionButtonTemplate, List<InteractionMenuItem> items, Vector2 position)
{
// Store a reference to the template for the list entries
InteractionButtonTemplate = interactionButtonTemplate;
// Store a reference to the character list element
interactionMenu = root.Q<ListView>("interaction-menu");
VisualElement mainContainer = root.Q<VisualElement>("main-container");
mainContainer.style.position = Position.Absolute;
mainContainer.style.left = position.x + menuOffset;
mainContainer.style.bottom = position.y + menuOffset;
mainContainer.style.display = DisplayStyle.Flex;
fillInteractionList(items);
}
void fillInteractionList(List<InteractionMenuItem> items)
{
// Set up a make item function for a list entry
interactionMenu.makeItem = () =>
{
// Instantiate the UXML template for the entry
var newListEntry = InteractionButtonTemplate.Instantiate();
// Instantiate a controller for the data
var newListEntryLogic = new InteractionMenuButtonController();
// Assign the controller script to the visual element
newListEntry.userData = newListEntryLogic;
// Initialize the controller script
newListEntryLogic.SetVisualElement(newListEntry);
// Return the root of the instantiated visual tree
return newListEntry;
};
// Set up bind function for a specific list entry
interactionMenu.bindItem = (item, index) =>
{
(item.userData as InteractionMenuButtonController).SetInteractionMenuItem(items[index]);
};
// Set a fixed item height
interactionMenu.fixedItemHeight = 45;
// Set the actual item's source list/array
interactionMenu.itemsSource = items;
}
When clicking the other gameObject an entirely different set of options may be displayed. I figured calling the same logic with a different set of InteractionMenuItem would do the trick. However it seems like the bindItem logica is being called with the oldset of data. Which causes a index out of range error for items[index].
The part where im really lost is, with my current logic i display none the visual element again if no gameObject (or no interactable gameObject is selected). If i do that between switching from gameObject 1 to 2 all is fine. However triggering the same logic just before i repopulate the list does not have the same effect (and i would consider it a dirty workaround)
There must be something im not getting.