Search Unity

Question IndexOutOfRangeException

Discussion in 'Scripting' started by bugzyhamster, Dec 5, 2022.

  1. bugzyhamster

    bugzyhamster

    Joined:
    Nov 25, 2022
    Posts:
    8
    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? :(

    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:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Flashlight : MonoBehaviour
    6. {
    7.     [SerializeField] GameObject FlashlightLight;
    8.     [SerializeField] private bool useFlashlight = false;
    9.     [SerializeField] private bool FlashlightActive = false;
    10.  
    11.     [SerializeField] private AudioSource flashlightAudioSource = default;
    12.     [SerializeField] private AudioClip[] flashlightOn = default;
    13.     [SerializeField] private AudioClip[] flashlightOff = default;
    14.  
    15.     // Start is called before the first frame update
    16.     void Start()
    17.     {
    18.         FlashlightLight.gameObject.SetActive(false);
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update()
    23.     {
    24.         if (useFlashlight == true)
    25.         {
    26.             if (Input.GetKeyDown(KeyCode.F))
    27.             {
    28.                 if (FlashlightActive == false)
    29.                 {
    30.                     FlashlightLight.gameObject.SetActive(true);
    31.                     FlashlightActive = true;
    32.                     flashlightAudioSource.PlayOneShot(flashlightOn[UnityEngine.Random.Range(0, flashlightOn.Length - 1)]);
    33.                 }
    34.                 else
    35.                 {
    36.                     FlashlightLight.gameObject.SetActive(false);
    37.                     FlashlightActive = false;
    38.                     flashlightAudioSource.PlayOneShot(flashlightOff[UnityEngine.Random.Range(0, flashlightOff.Length - 1)]);
    39.                 }
    40.             }
    41.         }
    42.     }
    43. }
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    Random.Range is max exclusive according to the documentation. That means your maximum should be flashlightOn.Length, don't subtract 1 from it.
     
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,911
    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:

    Code (CSharp):
    1. int soundIndex = Random.Range(0, flashlightOn.Length - 1);
    2. Debug.Log("Random On Index: " + soundIndex);
    3. Debug.Log("FlashLight On Length: " + flashlightOn.Length);
    Notably when the collection's are empty, they are always going to throw an error.
     
    Bunny83 likes this.
  4. bugzyhamster

    bugzyhamster

    Joined:
    Nov 25, 2022
    Posts:
    8
    [
    I'm sorry I'm relatively new to C#, where would I put this?
     
  5. bugzyhamster

    bugzyhamster

    Joined:
    Nov 25, 2022
    Posts:
    8
    I got rid of the "- 1" but I still get the same error.
     
  6. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,911
    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:
    Code (CSharp):
    1. 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.
     
    bugzyhamster and Bunny83 like this.
  7. bugzyhamster

    bugzyhamster

    Joined:
    Nov 25, 2022
    Posts:
    8
    THANK YOU so much! I ended up fixing the problem <33333 I will learn more about Debug.Log so this won't happen again :D
     
    Kurt-Dekker, Bunny83 and spiney199 like this.
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    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://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    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://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    When in doubt, print it out!(tm)

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

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    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).
     
  10. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    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.
     
  11. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    Well, I wasn't asking for the variable names, but the values ;-)

    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
    Code (csharp):
    1.  
    2. Debug.Log(index + ", " + array.Length);
    3.  
    @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.
     
    Last edited: Dec 6, 2022
  12. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,474
    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.

    Exception.png
     
    spiney199 likes this.