Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Problem with: IndexOutOfRangeException: Array index is out of range.

Discussion in 'Scripting' started by Nadan, Dec 23, 2013.

  1. Nadan

    Nadan

    Joined:
    Jan 20, 2013
    Posts:
    341
    I have a dialog in the game (sentence per wav file) that I have put in array.

    Code (csharp):
    1. var sentence : AudioClip[];
    2.  
    3. function Update ()
    4. {
    5.  
    6.     if (gameVariables.gamestate == 1)
    7.    
    8.     {
    9.         print(sentence.Length);
    10.        
    11.         dialog ();     
    12.         gameVariables.gamestate = 2;   
    13.    
    14.     }
    15.  
    16. }
    17.  
    18. function dialog ()
    19.  
    20. {
    21.  
    22.     audio.clip = sentence[0];
    23.  
    24.     audio.Play();
    25.  
    26.     yield WaitForSeconds (audio.clip.length);
    27.  
    28.     audio.clip = sentence[1];
    29.  
    30.     audio.Play();
    31.  
    32.     yield WaitForSeconds (audio.clip.length);
    33.  
    34.     audio.clip = sentence[2];
    35.  
    36.     audio.Play();
    37.  
    38.     yield WaitForSeconds (audio.clip.length);
    39.  
    40. }
    At first this works fine. I can hear the sounds etc. But for some reason without me changing (at least that I know) anything it starst to suddenly say: "IndexOutOfRangeException: Array index is out of range.".

    I can see in the inspector that there are sounds. If I delete the gameobject that has this script, make a new one, it again works for some time. Couple of times that I run the game. Then stops working. Strange. Any ideas what I'm doing wrong here?

    I also added the Debug "print(sentence.Length); " and it gives zero. That's the problem but why is it suddenly giving zero since in the inspector it's clear that there are wav files.

    EDIT:

    If I call this function from another gameobject it works again. But why? I have no idea.

    Code (csharp):
    1. var tarina = GameObject.FindWithTag("eventti");
    2. tarina.GetComponent(eventsVillage).dialog ();
     
    Last edited: Dec 23, 2013
  2. DWORD

    DWORD

    Joined:
    Jun 22, 2010
    Posts:
    38
    Do you have more than one game object with this script?

    All game objects with this script attached has the array filled with at least 3 sounds?

    Do you use Awake() and/or Start() to change the values in this array (or any other function for that matter)?