- Home /
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 :/
// 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);
}
Don't know if this is correct, but are you not setting all gameobjects to false when you run your foreach?
foreach(GameObject secondaryWeapon in secondaryWeapons) {
secondaryWeapon.SetActive (false);
}
i want to set all false and then i set the selected weapon true
I think it would be better to just instantiate/destroy instance weapon then just activate/deactivate.
Or try something like this:
foreach(GameObject SecWeapon in secWeapons){ if(curSecWeapon.name != SecWeapon.name) SecWeapon.SetActive(false); else SecWeapon.SetActive (true); }
Answer by Fabkins · Feb 09, 2014 at 01:04 PM
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.
with enum the game goes the same way, i can change weapon, but the script attached to it don't play, the OnGUI of the script play, but the inputs and etc dont work
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Plane - 10x10 grid - Questions about it. 1 Answer
Array.Count returning 0 out of the foreach and 4 inside 1 Answer
Array foreach problem 1 Answer
Disable All Transform In List 1 Answer