Error IndexOutOfRangeException

I keep on getting this error whenever my code is run. The code is meant to generate a random index within an array to select a prefab from a list defined by a certain tag (B). The issue is that the unity console is saying that the index given is outside of the range inside the array, which it shouldn’t be. I have no idea why this is happening, and Debug.Log has been little help. Any assistance would be greatly appreciated!

private void Start()
    {
        Invoke("Spawn", 0.1f);
        Invoke("Array", 0.05f);
    }
    public void Array()
    {
        TopObjects = GameObject.FindGameObjectsWithTag("T");
        BottomObjects = GameObject.FindGameObjectsWithTag("B");
        LeftObjects = GameObject.FindGameObjectsWithTag("L");
        RightObjects = GameObject.FindGameObjectsWithTag("R");
    }

    private void Spawn()
    {
        if (spawned == false)
        {
            if (openingDirection == 1)
            {
                // bottom room spawn
                rand = Random.Range(0, BottomObjects.Length);
                BottomObjects[rand] = BottomObject;
                BottomObject.SetActive(true);
                BottomObject.transform.position = transform.position;
                BottomObject.transform.rotation = Quaternion.identity;
                Debug.Log(rand);
            }
        }
    }

Is it possible that there are zero objects in this array?

Your Debug.Log might be unhelpful because it’s after the line where the exception is presumably happening, so it doesn’t get to the Debug.Log when you have a problem. Try logging BottomObjects.Length before accessing the array at all.

Why are you using Invoke() in that way? Why not just call Array() at the beginning of Spawn()? I’m not sure I’d trust Invoke to call those in a predictable order if, for example, you have a frame 1 that lasts for more than 0.1 second (not at all unusual for a first frame).

1 Like

Sorry, i forgot to mention that i am attempting to use object pooling for the first time, so my code might be a bit iffy. The objects with the tag are instantiated with start(), so i was using Invoke() to delay the start of Array() so that the FindGameObjectsWithTag would actually register the objects

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

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

Look also for a stray extra copy of your script on some other object that you didn’t intend to drop it on.