Question by
Robby222 · Jun 06, 2016 at 09:37 PM ·
errorarrayaudioindexoutofrangeexceptionout of range
Array index is out of range (C#)?
I'm trying to make a audio visualizer in Unity. Want a sphere to resize as reaction on the music.
I keep getting this error: "IndexOutOfRangeExeption: Array index is out of range." Ok, because I'm new to this scripting thing, I don't know how to fix it. t's probably really simple, but we al got to start somewhere, right?
So here is my script:
using UnityEngine;
using System.Collections;
public class Spechtrum : MonoBehaviour {
public GameObject[] sphere;
public int numberOfObjects3 = 20;
void Start () {
sphere = GameObject.FindGameObjectsWithTag ("sphere");
}
void Update () {
float[] mid = AudioListener.GetSpectrumData (1024, 0, FFTWindow.Hamming);
//The next line is the error line.
for (int i = 0; i < numberOfObjects3; i++) {
Vector3 previousScale = sphere [i].transform.localScale;
previousScale.y = mid [i] * 10;
previousScale.x = mid [i] * 10;
previousScale.z = mid [i] * 10;
sphere [i].transform.localScale = previousScale;
}
}
}
I was wondering if anyone could help me?
Comment
Best Answer
Answer by Raresh · Jun 06, 2016 at 09:39 PM
for (int i = 0; i < sphere.Length; i++)
{
Vector3 previousScale = sphere [i].transform.localScale;
previousScale.y = mid [i] * 10;
previousScale.x = mid [i] * 10;
previousScale.z = mid [i] * 10;
sphere [i].transform.localScale = previousScale;
}
Changed the for loop, now it will only loop through the contents of the array, guaranteeing you won't get out of the range. Now i don't know what's the size of "mid" but if it's the same, you shouldn't be getting any errors.
Wow! Thx man! You really helped me! And you responded really quik! Thanks!