IndexOutOfRangeException

I’m making a script to play a sound when I turn on and off my flashlight, and I get these errors. How do I fix this? :frowning:

IndexOutOfRangeException: Index was outside the bounds of the array.
Flashlight.Update () (at Assets/Scripts/Flashlight.cs:32)
IndexOutOfRangeException: Index was outside the bounds of the array.
Flashlight.Update () (at Assets/Scripts/Flashlight.cs:39)

Here is my code:

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

public class Flashlight : MonoBehaviour
{
    [SerializeField] GameObject FlashlightLight;
    [SerializeField] private bool useFlashlight = false;
    [SerializeField] private bool FlashlightActive = false;

    [SerializeField] private AudioSource flashlightAudioSource = default;
    [SerializeField] private AudioClip[] flashlightOn = default;
    [SerializeField] private AudioClip[] flashlightOff = default;

    // Start is called before the first frame update
    void Start()
    {
        FlashlightLight.gameObject.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {
        if (useFlashlight == true)
        {
            if (Input.GetKeyDown(KeyCode.F))
            {
                if (FlashlightActive == false)
                {
                    FlashlightLight.gameObject.SetActive(true);
                    FlashlightActive = true;
                    flashlightAudioSource.PlayOneShot(flashlightOn[UnityEngine.Random.Range(0, flashlightOn.Length - 1)]);
                }
                else
                {
                    FlashlightLight.gameObject.SetActive(false);
                    FlashlightActive = false;
                    flashlightAudioSource.PlayOneShot(flashlightOff[UnityEngine.Random.Range(0, flashlightOff.Length - 1)]);
                }
            }
        }
    }
}

Random.Range is max exclusive according to the documentation. That means your maximum should be flashlightOn.Length, don’t subtract 1 from it.

The errors tell you what is happening. You’re trying to access a collection with an index that is either too small (below 0), or too large (greater than the last index).

Debugging these yourself is an important part of coding. Some simple Debug.Log statements would’ve helped you narrow down the issue and get you to a quick solution:

int soundIndex = Random.Range(0, flashlightOn.Length - 1);
Debug.Log("Random On Index: " + soundIndex);
Debug.Log("FlashLight On Length: " + flashlightOn.Length);

Notably when the collection’s are empty, they are always going to throw an error.

1 Like

[

I’m sorry I’m relatively new to C#, where would I put this?

I got rid of the “- 1” but I still get the same error.

Just wherever you expect the code to execute, so you may get meaningful information about what values are actually being produced to work out precisely how the errors are being caused.

You can also give a second parameter which is the ‘context’ that the code is running in:

Debug.Log("FlashLight On Length: " + flashlightOn.Length, this);

this referring to the monobehaviour that is running this particular code, so that when you click on the debug entry in your console it highlights the object that fired it. This is helpful as often the problem is an errant extra component you didn’t realise was there.

And like I said:

So you might want to guard against empty collections.

2 Likes

THANK YOU so much! I ended up fixing the problem <33333 I will learn more about Debug.Log so this won’t happen again :smile:

3 Likes

Oh yes, good stuff that logging is… you will soon wonder how you did anything without it!

Here’s my blurb about Index Out of Range:

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

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

Steps to success:

  • find which collection it is (critical first step!)
  • find out why it has fewer items than you expect
  • fix whatever logic is making the indexing value exceed the collection
  • remember you might have more than one instance of this script in your scene/prefab

And here’s my blurbs about Debug.Log():

You must find a way to get the information you need in order to reason about what the problem is.

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

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

IF you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

When I get an IndexOutOfRangeException, I’m always wondering why this message is so sparse. I mean, I of course enjoy adding some Debug.Log’s to my code, but it makes sense to me that the error message would simply include the passed index that is out of range and the range of the array it is used in. That would probably save a few million hours of work a year worldwide.

IndexOutOfRangeException: Index (-1) was outside the bounds of the array (0 to 5).

Wouldn’t that be lovely.

On your specific code, it might well be the case that those arrays have no elements, so the length is 0. Random.Range probably just returns 0, but that’s still out of range since the array is empty.

IndexOutOfRangeException: Index (0) was outside the bounds of the array (empty).

Some languages do this, but remember that the index checking must also exist in the lowest most compact machine language individual CPU instruction stream.

In C, C++, C# and a lot of high performance langauges, your array / list is just a pointer into memory somewhere, like memory location 0x07f331808

The name of most of your variables are long gone by that point. To put in code and data to retain and relink variable names just so you can more quickly find your bug isn’t really a priority for high-performance language designers.

Well, I wasn’t asking for the variable names, but the values :wink:

I don’t want to get too technical, but it makes sense that if you are able to determine that the index is out of range, you are also able to determine what the index and range are. Whether that’s in the most compact form or somewhere outside of that where the error handling it further dealt with.

And indeed it might not be a priority, but honestly, so many hours are wasted on adding a

Debug.Log(index + ", " + array.Length);

@MelvMay Indeed, it’s related to .net in general, not Unity specifically. And I must admit that I’ve exchanged using a debugger for adding println’s about 25 years ago, it just allows for more specific feedback.

AFAIK this exception is a common language runtime exception, it’s not implemented by Unity.

I’d be suprised if that were the case unless you cannot attached a debugger which stops exactly at the call-site showing you everything.

8639865--1161978--Exception.png

1 Like