Hello, I am new to arrays. I want to have an array containing 3 float values, which I am able to declare. The console gives error for the last line: “Array index is out of range”.
using UnityEngine;
using System.Collections;
public class ChangeArray : MonoBehaviour {
//public string[] myArray = new string[2];
public float[] myArray2 = new float[2];
// Use this for initialization
void Start () {
// myArray[0] = "first value";
// myArray[1] = "second value";
// myArray[2] = "third value";
myArray2[0] = 5f;
myArray2[1] = 10f;
myArray2[2] = 15f;
}
}
The size of your array is 2, but you are putting three values in it. This line:
public float[] myArray2 = new float[2];
…creates an array with 2 slots (0 and 1). Note that since the array is public, changing the 2 to 3 will not fix the problem. You need to either make the change in the Inspector, change the size and in the Inspector use the Reset for this object, or change the value and make the array private. I vote for the last if it doesn’t interfere with something you have planned.
Thank you guys for help!
Robertbu, I named it public, because I was not quite sure what the difference and limitation of private was, apart from being hidden from the inspector. I thought private variables could only be accessed inside a single script and therefore could not be got by using .GetComponent script, to get the value for another script. 