Good morning, I have a problem when passing a second list as a parameter after having done it with the first one through the same function. It turns out that when I do that with the first list, it removes Vector2 objects from the points list, leaving about 4 Vector2 objects that will be assigned to 4 gameObjects.transform.localPosition objects, but when passing the second list, despite matching everything, it gives me an “out of range” error when it turns out that everything matches, and positions are blown. How do I correct this? How do I make it so that doing this with future lists that passes as a parameter does not happen the same? I’ll show you code and screenshots:
Please use the code tags. Screenshots make it impossible to cut and paste your code to make changes and it’s hard to refer to specific parts of your code without line numbers. Also, showing the error without the line number makes it harder and take longer to figure out the issue. Accuracy is key.
However, the issue here is most like where you remove from points list. Removing items from a list inside a loop is often a problem unless you’re iterating backwards. Calling RemoveAt(xyz) reorders the elements in the points list, so if points has 6 items (indexs 0,1,2,3,4,5) and you call points.RemoveAt(1), points.RemoveAt(2), points.RemoveAt(3), it will have 3 items left at index 0,1,2. I suspect on the 4th (or sooner) time through the loop you’re trying to access points[3] it no longer exists because it has less than 4 elements left.
Online documentation remarks for RemoveAt:
When you call RemoveAt to remove an item, the remaining items in the list are renumbered to replace the removed item. For example, if you remove the item at index 3, the item at index 4 is moved to the 3 position. In addition, the number of items in the list (as represented by the Count property) is reduced by 1.
The most common way to avoid this is to create a temporary list for the points you want to remove, add them to that temp list in the loop, then once the loop is done, loop through your temporary list and remove those points using Remove(item), not RemoveAt(index). If you want to use RemoveAt you must use a for loop and iterate backwards.
You should use code tags, having line numbers will definitely help on pointing to the right location. Same with error, show the full error since it gives the line number.
You should be using a for loop instead of a foreach. You are not using the item at all instead you are using the index.
Your issue is probably when removing an element from points array. Since you are removing the used index.
Before starting the loop: index 0, points count 4
RemoveAt 0, points count 4, new count 3
RemoveAt 1, points count 3, new count 2
RemoveAt 2, points count 2. Element 2 doesn’t exists since the count is 2. ArgumentOutOfRange is thrown here.