- Home /
Find the index of a GameObject within an array
Please can someone help me with finding the index of a gameobject in an array as I loop through it?
Basically, I have an array of Gameobjects, and I want to enable the selected weapon, and disable all the others.
I have written the following code which I assumed would work fine, but when I call this, all gameobjects simply de-activate.
Can someone see if I have done anything wrong here?
public void ChangeWeapon(int weaponID)
{
int weaponToChangeTo = weaponID;
for (int i = 0 ; i < weapons.Length; i ++)
{
if (System.Array.IndexOf(weapons, i) != weaponToChangeTo)
{
weapons[i].SetActive(false);
}
if (System.Array.IndexOf(weapons, i) == weaponToChangeTo)
{
weapons[i].SetActive(true);
}
}
}
The 2 answers below provide a better solution for your problem ... but to answer your question "Can someone see if I have done anything wrong here?": Yes :) The method you are using is [IndexOf(Array, Object)][1]
. That means in your code you are searching for the object "i" in the array "weapons" which doesn't exist. So the returned index is (generally) always -1 and always != weaponToChangeTo
.
[1]: https://msdn.microsoft.com/en-us/library/7eddebat%28v=vs.110%29.aspx
Thanks for that, I was struggling to understand why my code wasnt working, thats very helpful :)
Answer by CharlieMcF · Oct 12, 2015 at 11:32 PM
I think you might be overthinking this problem.
You're passing the Index of the weapon you want to change to. This means you want that weapon to be active, and all others to be inactive.
Rather than doing what you are currently doing, I would simply loop through all of the weapons in your array, and set them to be Inactive. Once this loop is complete, simply set the weapon at your desired index to be active.
Eg:
public void ChangeWeapon(int weaponID)
{
for (int i = 0 ; i < weapons.Length; i ++)
{
//Set All weapons inactive
weapons[i].SetActive(false);
}
//Test to ensure that the desired index does not exceed the array length
if(weaponID < weapons.Length)
{
//Set the desired weapon to be active
weapons[weaponID].SetActive(true);
}
}
Hope that helps! (And apologies for the wonky code-formatting)
Fantastic, that worked a charm and is certainly a lot simpler too :)
Answer by _Adriaan · Oct 12, 2015 at 11:32 PM
Why not:
public void ChangeWeapon(int weaponID)
{
for (int i = 0 ; i < weapons.Length; i ++)
weapons[i].SetActive(i == weaponID);
}
?
Your answer
![](https://koobas.hobune.stream/wayback/20220612041050im_/https://answers.unity.com/themes/thub/images/avi.jpg)