I tried to delete last element in inpInnov using inpInnov.RemoveAt(inpInnov.Count - 1);. However I was getting an error “ArgumentOutOfRangeException”, then I wrote%
Your code and your description has some conflicting information. This makes it really difficult to tell what you’re actually doing. You said you want to remove the last element but the code you have shown removes the first while printing the index of the last one. We don’t know if the two log messages do actually correspond to those two lines, have you checked the stacktrace?
Where / when is this code executed? Does the error happen consistently / can be repeated consistently? Is there any funky multi-threading going on?
We can not debug your code for you, especially when we don’t have the code nor the context. List.RemoveAt certainly does not have a bug.
@appleLk This might be a little late, but could you share more of the code you wrote so we get better context of what’s going on?
The RemoveAt() method takes the index of the item you want to remove from the list as an argument. In this case, that will be the index of the item you want to delete from the list inpInnov.
If the index supplied to this method is less than 0, you’ll get an ArgumentOutOfRangeException because the index can only be 0 itself or a positive number less than the total items in the list.
It looks like there’s just one item in the list because running Debug.Log(inpInnov.Count - 1) returns 0. so theoretically, the code should work.
Here are some things you can try to fix the problem.
Are you trying to remove the last item using Count - 1 as the index?
Check if something else removes the item from the list before you call the RemoveAt() method. If this is the case, then the list will be empty by the time you try removing the item, and the index passed will be negative causing the exception.
Some other line of code could be the problem.
Even though the log statements are close. the code you shared may not be the issue. Check for other methods interacting with the list and see if they’re using the correct index.
Are you trying to remove the first item instead?
Lists are zero-indexed, so the first item in the list has an index of 0. Passing 0 in inpInnov.RemoveAt(0) will remove the first item. Unless of course there’s exactly one item in the list, then that item becomes the first and last item by default.
By the way, when naming list variables, constants, etc., it’s a common convention to use the plural version of the name describing the items.
// A list of weapons will be called 'weapons'
var weapons = new List<string>()
{
"Pistol",
"Rifle",
"Sword"
};