Script gives out of bounds error, but only if I don't replace the script on the game object

I decided to spend some time making a version of the watermelon game as a personal exercise today and ended up encountering some issues. There are 2 main problems that have been causing issues for me that I have never seen before and feel completely unrelated to my logic (although it could for sure be because of my logic). I’m only gonna go into the first of these right now which is that when I open the project and run it, I get an out of bounds error from a list in one of my scripts, however, everything seems fine with it and when logging the script in a debug.log, it shows all the elements that are expected to be in there. The only thing that seems to make it stop giving that error is if I remove the script from the object and put it back on. The script has no variables that need to be filled out in the editor that could be throwing this off and this issue persists even if I save, close the project, and then reopen it. I have attached the script that has been causing this issue just in case, any help is appreciated.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FruitRandomizer : MonoBehaviour
{
    const int maxFruit = 3;
    const int maxQueueSize = 10;

    GameManager gameManager;

    private List<GameObject> fruitPrefabs = new List<GameObject>();

    //the queue of upcoming fruit
    private Queue<GameObject> fruitQueue = new Queue<GameObject>();

    private void Start()
    {
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();

        fruitPrefabs = gameManager.fruitPrefabs;

        //fills the queue to start
        for (int i = 0; i <= maxQueueSize; i++)
        {
            AddNewFruit();
        }
    }

    private void AddNewFruit()
    {
        //adds a random fruit from the first couple of sizes to the queue
        GameObject temp = fruitPrefabs[Random.Range(0, maxFruit)];
        fruitQueue.Enqueue(temp);
    }

    public GameObject PullFromQueue()
    {
        //refills the queue before pop
        AddNewFruit();
        return fruitQueue.Dequeue();
    }
}

At a minimum I see an unchecked collection access on line 33, both unchecked in size and unchecked in checking that there is even at least one element in an array. See more notes below.

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

http://plbm.com/?p=236

Steps to success:

  • find which collection it is and what line of code accesses it <— (critical first step!)
  • find out why it has fewer items than you expect
  • fix whatever logic is making the indexing value exceed the collection size

Remember also:

  • a collection with ZERO elements cannot be indexed at all: it is empty
  • you might have more than one instance of this script in your scene/prefab
  • the collection may be used in more than one location in the code
  • indices start at ZERO (0) and go to the count / length minus 1.

This means with three (3) elements in your collection, they are numbered 0, 1, and 2 only.

Time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

I’ve already gone through and done a debug.log at all spots that there could be issues with it and everything came back how I expected it to. It is copying over a filled list from the other script that it references where it has a max value of 5 and the highest value it goes to is 2 when being called in this script. I have already checked to make sure that there is no duplicate of the script in the scene and have also tried rebuilding it from a fresh project, reloading the libraries, and restarting my computer. However, with all of these, the issue persists and the only thing that stops the errors is removing the script and adding it back every time i launch my project.

It would help to tell us where the error actually occurs. The error message also tells you the line it happens on, so that should be the first place you start debugging.

its at line 33 and i’ve already checked to see that everything goes in and out of it exactly how I expect it to

What is actually calling PullFromQueue() though? Is something potentially calling it before Start() has been called, or also trying to call it in Start() leading to order of execution issues. Maybe this initialisation should be done in Awake?

Thank you, switching it to be done in Awake instead seemed to have solved it. I wasn’t even thinking about the fact that the PullFromQueue method was being called as part of another scripts Start which had a lot less to execute in it. It’s still kinda confusing why removing the script from the object and then putting it back on made the errors disappear though previously, but at least it works now.

Likely removing it and adding the component put it onto the end of order of execution. Closing and reopening the project would potentially load it into that order earlier.

In any case the per-object/type order of execution within the same callback shouldn’t be relied upon, which is why we have Awake, Start, and OnEnable to space things out. Important lesson learnt.