I’m trying to access an array from another script in C# but it always give me index out of range error.
script1.cs (attached to mainCamera named MC)
public int[] testArray = {1,2,3,4};
script2.cs (attached to one of the prefabs)
public int[] NEWtestArray;
NEWtestArray[0] = MC.GetComponent<script1>().testArray[0]; //gives an index out of range
//tried to debug
Debug.log(MC.GetComponent<script1>().testArray[0]); //same error
//but if I do this
NEWtestArray = MC.GetComponent<script1>().testArray;
Debug.log(NEWtestArray[0]); //this works and would output 1.
So, how can I access individual elements without copying the entire array? I’m using the main array in the camera to pull large amount of static game data from an xml file. It just doesn’t make sense to copy this entire array over to each of the objects in the scene that need individual data from this array.
First, I want to clarify in my original post, my declaration of the array is wrong. In my code, I actually declare the array as:
public int[] testArray;
Start (){
testArray = new int[] {1,2,3,4};
}
Second, I found out why I was getting the error. While both of part of array code is initialize in the Start() function of script1 and script2, for some reasons script2 was always initialized before script1, therefore, when script2 look for the array, it did not exists. During my search today, I found out that the Awake() function always initialize before the Start() function. So I moved my array code in script1 from Start() to Awake() and now everything is working as it should.