Array index is out of range C#

|EDIT|
I changed the name of days to dayOfWeek and that seems to have fixed it? Does Unity use “days” for anything else? I couldn’t find it anywhere in the API list…
Thanks for the help anyway!

//

Feels like I’ve read through almost a hundred threads with the same question, but I’m still stuck with my error, so here goes:

I have this really simple script with 2 arrays to basically run through 16 days. For now I just wanted to log them to see if they work as intended, but I’m getting the index out of range error.

This is my code:

    private string[] timeOfDay;
    int timeOfDayCounter = 0;

    private string[] days;
    int dayCounter = 0;
	
	void Start () {
        timeOfDay = new string[4] { "Morning", "Afternoon", "Evening", "Night" };
        days = new string[16] { "Day 1", "Day 2", "Day 3", "Day 4", "Day 5", "Day 6", "Day 7", "Day 8", "Day 9", "Day 10", "Day 11", "Day 12", "Day 13", "Day 14", "Day 15", "Final Day"};
    }

    public void DisplayTime()
    {
        Debug.Log(days[dayCounter]);
        Debug.Log(timeOfDay[timeOfDayCounter]);
    }
	
    public void UpdateTime()
    {
        timeOfDayCounter += 1;
        if (timeOfDayCounter > 3)
        {
            timeOfDayCounter = 0;
            dayCounter += 1;
        }
    }

DisplayTime and UpdateTime are called in a separate script on click (in that order), and the first time it runs the first line in DisplayTime, it throws the error.

I’ve tried setting the arrays as private, but it didn’t help. The arrays exist in the inspector when I start the game, so they’re definitely not empty.
68404-arrays.png

If I log the Counters, they seem to work as intended. I’ve tried using a couple set numbers to log the arrays, but it still gives the error. A friend told me to try and log them as this.array[#], but that didn’t do it either.

I feel like I’m missing something incredibly obvious, I’m just trying to see what’s in my arrays?

Two problems here:

  1. Your timeOfDayCounter - overflow check is “> 4”, but any C# array starts with 0, so if timeOfDayCounter == 4, it is already too late. You want to check to “>= 4”.
  2. You never check dayCounter. You probably just missed a similar check that resets the dayCounter to 0 if its >= 16.

Btw… another way of increasing a counter that should keep inside an arrays bound is:

timeOfDayCounter = (timeOfDayCounter + 1) % timeOfDay.Length;

The % - operator will ensure that the value goes back to 0 if it reaches the array length. (Note, that this trick does not work with decrementing. The % operator will go negative)