Struct array not finding index

Hey all, I have an array of structs with different variables for my inventory system. When I store items that stack I just add them that many times to the inventory, so the inventory just has duplicates of the same struct for every instance.

At the current moment if I have 10 apples in my inventory, and I try to find 5 apples and remove them, it usually succeeds and removes them. But occasionally despite having 10 apples in my array it can’t find all of them and returns -1 on the find.

I have printed out the entire inventory and it’s always the same thing in each array slot for the name variable for example, and then I instead I did a for each loop and broke the inventory struct and dropped item struct to see if the name matched. And again in most cases it was fine, but some it couldn’t find the match for some reason.

I’m probably doing something stupid, or forgot something. I can provide more info if needed for whatever would be helpful, wasn’t sure if more was needed. If anyone can help me out, it would be greatly appreciated! Thanks! :slight_smile:

Edit: This is the other method I tried. Works for a few times, and then all of the sudden it throws an error despite everything still matching:

Hi Krozjin,

With the second code - just change to a “Reverse For Each” and see if that works… Removing items from the array affects the “For Each” - the indexes all change…

2 Likes

As @RecourseDesign mentioned, when you are working with arrays it can sometimes be painful when it comes to removing individual elements / indexes. When you remove say index 7 of 10, your index that was 10 is now 9.

2 Likes

That’s a good point, thanks for that insight. Never heard of that node till now, but it doesn’t seem like there’s a break option for it. So if I do try to remove items from the array using the Reverse for Each Loop I can’t tell it to stop without a break, it’ll just remove everything, right?

One breakfast later my brain starts working and I got this setup now, and it works!

Thanks guys for teaching me about the Reverse for Each Loop! Great node I didn’t know about before. :smiley:

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.