Array simple problem

What’s wrong with the second code? the two codes do the same, but in the second code, the script attached to the GameObject doesn’t play or dont work, in the first script all works correctly but when i have much weapons the script will be giant :confused:

// First Code

if(currentSecondaryWeapon == "M9") {
			secondaryWeapons[0].SetActive (true);
			secondaryWeapons[1].SetActive(false);
		}
else if(currentSecondaryWeapon == "Glock") {
			secondaryWeapons[0].SetActive (false);
			secondaryWeapons[1].SetActive(true);
		}

// Second Code

if(currentSecondaryWeapon == "M9") {
			foreach(GameObject secondaryWeapon in secondaryWeapons) {
				secondaryWeapon.SetActive (false);
			}
			secondaryWeapons[0].SetActive (true);
		}
else if(currentSecondaryWeapon == "Glock") {
			foreach(GameObject secondaryWeapon in secondaryWeapons) {
				secondaryWeapon.SetActive (false);
			}
			secondaryWeapons[1].SetActive (true);
		}

I cannot see anything obviously wrong with the code but I would suggest is you trace bomb the code by adding Debug.Log line at every point you set something.

I would also suggest you structure your code such that you first run the loop to clear the setactive flag (currently you do this in a for loop).

Then you use a “switch” statement to set active.

eg

foreach(GameObject secondaryWeapon in secondaryWeapons) 
{          
   secondaryWeapon.SetActive (false);         
}

switch(currentSecondaryWeapon )
{
case "M9":
  secondaryWeapons[0].SetActive (true);
  break;
case "Glock":
   secondaryWeapons[1].SetActive (true);
   break;
}

Lastly, instead of brute force clearing every weapon, why dont remember which is the last weapon you selected and clear it.