- Home /
Array index out of range when access from another scrip
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.
Answer by Marionette · Jan 28, 2014 at 09:14 PM
make sure that the array is actually being created properly in script1 first. I would do something like this to test it:
public int[] testArray = null;
then in awake/enable/start (wherever you need to initialize)..
declaring it static might also help ;)
Answer by Xtro · Jan 28, 2014 at 08:04 PM
Don't set the default values when defining the members.
Write this into the Start event
testArray = {1,2,3,4};
Can you please mark the correct answer if you fixed that problem?
Answer by nggb · Jan 29, 2014 at 07:51 AM
Thanks for all the answers.
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613131925im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to FindChild RectTransform and access its Text 2 Answers
Need an advise, how to find all objects with a specific name and a specific script? 2 Answers
Take array and waypoints from parent spawnner 2 Answers
Create array of scripts 1 Answer
Obtaining an array of positions from an array of gameobjects 2 Answers