List: ArgumentOutOfRangeException

I’m trying to expand my knowledge of Lists and I’ve been experimenting the last few days. My current focus is on avoiding ArgumentOutOfRangeException: Argument is out of range errors when other functions or scripts are accessing a List that is constantly being updated.

Even checking if an element in a List is actually there before doing something can still result in these errors, so I am guessing between checking and doing, the List has changed.

Am I on the right track as to the cause? Or does anyone have some solid advice on how best to avoid out of index scenarios, or common causes?

Thanks!

How are you accessing your list(s)? Can you show some sample code?

That simply means you’re referring to an element that doesn’t exist. If the list.Count is 5, for example, then you can only use an index from 0-4. Anything else is out of range. That’s all there is to it.

That’s only possible if you changed the List yourself between checking and doing.

–Eric

Hi, thanks for the replies :slight_smile:

I have a script which is logging groups of vector3 information in a List. It’s elements are being removed, added, inserted and modified all the time. Groups are also being removed and added all the time.

The List uses a Class for it’s structure:

var testList = new List.<testClass>(); 

class testClass
{
	var id : String;
	var positions : List.<Vector3>();
}

I have an external script which is accessing (read only at the moment) elements of the list to display information.

It works but when I trigger lots of changes things get funky with:
NullReferenceException: Object reference not set to an instance of an object
…and…
ArgumentOutOfRangeException errors.

Have I found myself in some kind of data race?

I do check if an element exists before I try to do anything with it. For example

//groupPosition is the index number I am trying to retrieve
//positionNumber is the index number I am trying to retrieve

		if(testScript.testList.Count > groupPosition ) 
		{
			if(testScript.testList[targetPosition].positions.Count > positionNumber )
			{
				vector3Position = testScript.testList[targetPosition].positions[positionNumber] ;
			}
		}

Edit: After further testing it seems that trying positions.Count will error with a NullReferenceException as technically there is nothing there. Does this sound right? If so how would I check?

Edit 2: I have now added my own additional count in the class so I can keep track of how many positions there are. Not sure if the best solution but it works.

So all that leaves is the ArgumentOutOfRangeException errors.

Edit 3: Well I seem to have resolved the problems. Thanks for the inputs guys.