I keep getting an error on my for loop.

I’m trying to use this code for my for loop to print out the days in the calendar:

void OnGUI()
{
	for (i = 0; i < numOfDays + leadDays; i++) 
	{

		if (dates*.dateOfMonth == 0)*
  •   	{*
    
  •   		labelInput = " ";*
    

_ GUI.Label(new Rect ( 25, i * 10 ,200,50), labelInput);_

  •   	}*
    

_ if (dates*.dateOfMonth >= 1)_
_
{_
_ labelInput = dates.dateOfMonth.ToString();
GUI.Label(new Rect ( 25, i * 10 ,200,50), labelInput);
}
}
}*
but I keep getting this error:
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[Dates].get_Item (Int32 index) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
DatesDatabase.OnGUI () (at Assets/SCRIPTS/DatesDatabase.cs:147)
The code actually works fine but I keep getting this error and I’m worried that it might cause some bug later._

1 Answer

1

The error is caused due to your ‘numOfDays + leadDays’ value exceeds the length of dates.

Try to Debug.Log the values of your ‘i’ variable when you enter the for loop to check its value against the length of your dates.

I already changed the numofdays + leaddays to dates.count to make it more accurate and debugged the i and I get 31 which is the exact size of the dates list and I still get the error.

I see it now whenever it reaches the end of the loop it repeats itself, all I had to do was dates.count - 1. Thanks man!

array indexes start at zero, so the count should always be the array length less one