Can't access public static array from another class
Hi, I'm having a problem accessing the values in an array in another class. So far I have done this and not encountered any problems but in this instance I cannot get it to work.
Here is the relevant part of the first class:
public class Player : MonoBehaviour {
public static string[] playerTeam;
public void Start()
{
playerTeam = new string[32];
for (int i = 0; i < playerTeam.Length; i++)
{
int ir = System.Convert.ToInt32(System.Math.Floor((decimal)i / 2));
playerTeam[i] = Team.teamName[ir];
}
}
}
And the second class:
public class Team : MonoBehaviour {
public static string[] teamName;
public void Start () {
teamName = new string[16];
teamName[0] = "zero";
teamName[1] = "one";
teamName[2] = "two";
teamName[3] = "three";
teamName[4] = "four";
teamName[5] = "five";
teamName[6] = "six";
teamName[7] = "seven";
teamName[8] = "eight";
teamName[9] = "nine";
teamName[10] = "ten";
teamName[11] = "eleven";
teamName[12] = "twelve";
teamName[13] = "thirteen";
teamName[14] = "fourteen";
teamName[15] = "fifteen";
}
}
}
I want the stated int ir to be a number between 0 and 15, which works as intended. I then want to access the array teamName[] in the Team class, and get the appropriate team name from that array. For example, if i = 2, ir = 1, thus playerTeam[2] = Team.teamName[1].
When I try and use this, I get a null reference exception. However, there have been some cases where I have played around in Unity and managed to get it to work, but it does not work upon restart. I'm really confused and would appreciate any help.
Answer by NoseKills · Jul 18, 2017 at 06:43 AM
You populate the teamName array in Start method. There's no guarantee Team.Start() has run before Player.Start() so the array could well be null.
It might be possible to fix this using the script execution order settings but since the content of the teamName array really is static amd known before even starting the app, you can just declare and assign it statically so you can be sure it exists before any non-static method calls.
public static string[] teamName = new [] {
"zero",
"one",
"two",
...
}
Thank you very much. I had considered that it might be to do with the order the scripts were run, but had not been able to correct this with script execution order. Your method however has done exactly what I was looking for, thank you!
Your answer
Follow this Question
Related Questions
Null reference exception in an if statement that checks for it. 1 Answer
Convert string to array name? 0 Answers
Assigning to array give NullReferenceExecption!?!! 0 Answers
public vs private array in classes 0 Answers
Named array assigned to new array, named array returns null on all subsequent calls 0 Answers