- Home /
Unity c# indexoutofrangeexception: array index is out of range
Trying to assign 3 values to a array.
public string[] weaponList = new string[3];
the rest is inside start()
weaponList[0] = "Pistol";
weaponList[1] = "SMG";
weaponList[2] = "Shotgun";
Answer by perchik · Feb 21, 2014 at 09:49 PM
You should set weaponList = new string[3]; inside of start, not globally.
public string[] weaponList;
void Start(){
weaponList = new string[3];
weaponList[0] = "Pistol";
weaponList[1] = "SMG";
weaponList[2] = "Shotgun";
}
I tried that but got 2 error s
Only assignment, call, increment, decrement, and new object expressions can be used as a statement
the other one error CS1525: Unexpected symbol `='
That seems to work. Why does it not work if i assign it globally?
Nothing ever happens globally. When a script starts, the global variables are allocated, but they can't be initialized until a function actually runs. Unity runs Start() first, for that exact purpose.
If I solved your problem, please mark the answer as correct.
Your answer
Follow this Question
Related Questions
Can someone tell me what is wrong with this? 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Array index is out of range 2 Answers