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";

1 Answer

1

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 `='

–

whoops, had a stray ';' Edited.

–

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.

–