Array index out of range

whenever i run this script i get an error that says “Array index out of range” how do i fix this?

var weapons : GameObject[]; 

function Start () {
 
SelectWeapon(0);
 
}
 
function Update () {
 
if (Input.GetKeyDown("1")) SelectWeapon(0); 
 
if (Input.GetKeyDown("2")) SelectWeapon(1); 
 
}
 
function SelectWeapon(index : int){
 
for(var obj:GameObject in weapons)obj.SetActive(false); 
 
weapons[index].SetActive(true); 
}

the weapons array is not initialized.
You need to assign 2 values to it in Inspector before running the code

Hey…

You need to add at least 2 Objects in that array otherwise you will get this error.

To make it go away simply add length checking to your SelectWeapon function.

function SelectWeapon(index : int){
    if(index<weapons.length){
        for(var obj:GameObject in weapons)obj.SetActive(false);  
        weapons[index].SetActive(true); 
    }
}