Search Unity

Audio Array - Out of Index

Discussion in 'Scripting' started by hawx, Sep 28, 2015.

  1. hawx

    hawx

    Joined:
    Sep 29, 2012
    Posts:
    95
    Okay, basic thing here but I'm confused.....probably a bad day ;).

    This is the error I'm getting - On line 24. I don't see how it's trying to find something outside of the array. What am I missing.....?

    IndexOutOfRangeException: Array index is out of range.
    FFT_Analyser.Update () (at Assets/FFT_Analyser.cs:24)


    Code (csharp):
    1.  
    2. public class FFT_Analyser : MonoBehaviour {
    3.  
    4.     public GameObject prefab;
    5.     public int numberOfObjects = 20;
    6.     public float radius = 5f;
    7.     public GameObject[] bars;
    8.  
    9.     void Start() {
    10.         for (int i = 0; i < numberOfObjects; i++) {
    11.             float angle = i * Mathf.PI * 2 / numberOfObjects;
    12.             Vector3 pos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
    13.             Instantiate(prefab, pos, Quaternion.identity);
    14.         }
    15.         bars = GameObject.FindGameObjectsWithTag ("Bars");
    16.     }
    17.  
    18. //    Update is called once per frame
    19.     void Update () {
    20.         float[] Spectrum_Data = AudioListener.GetSpectrumData (1024, 0, FFTWindow.Hamming);
    21.         for(int i = 0; i < numberOfObjects; i++){
    22.             Vector3 previousScale = bars[i].transform.localScale;
    23.             previousScale.y = Spectrum_Data[i] * 40;
    24.             bars[i].transform.localScale = previousScale;
    25.         }
    26.     }
    27.  
    Best,
    Hawx

    PS. Yup I know it's not an FFT analyser.....well not yet.
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Don't use a seperate int variable for the condition in the loop when iterating a collection. Use bars.Length instead of numberOfObjects and you won't run out of range.
     
    portiexc likes this.
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    looks like you're working on the assumption that the instantiated objects are tagged "Bars"? if that is the case it would appear that none of them are?

    it would probably make much more sense to add the instantiated objects to the array as they are created rather than using a find function.