C# Set Current Array GameObject to Active

Hey, i am making a FPS and am currently working on a weapon switching and pickup system. I have a list of gameobjects (my weapons) but i am not sure how to set only the current weapon to active, does anybody know the solution? My current switching system also seems too complex and i am wondering if there is a better way to do this? :slight_smile: Thanks in advance

Here is part of my code:
public List weapons;
public int maxWeapons = 2;
public GameObject currentWeapon;
public int arrayPos = 0;

private void Start()
{
    
}

private void Update()
{
    //currentWeapon.SetActive(true);

    if ((Input.GetAxis("Mouse ScrollWheel") > 0f))
    {
        Debug.Log(weapons[arrayPos]); //Prints current value to console.
        if (arrayPos >= weapons.Count - 1)
        {
            arrayPos = 0;
        }
        else
        {
            arrayPos += 1;
        }
    }
    if ((Input.GetAxis("Mouse ScrollWheel") < 0f))
    {
        Debug.Log(weapons[arrayPos]); //Prints current value to console.
        if (arrayPos <= 0)
        {
            arrayPos = 1;
        }
        else
        {
            arrayPos -= 1;
        }
    }

This isn’t really too complex to be honest. One way you could shorten it is to:

//To change based on scroll input
arraypos = Mathf.RoundToInt(Input.GetAxis("Mouse ScrollWheel");

//To loop from 0 to weapons.Count
arraypos %= weapons.Count;

If you want to fire some event when you take a weapon out or put it away, this could be done quickly as:

int scroll;

void Update(){
     scroll = Mathf.RoundToInt(Input.GetAxis("Mouse ScrollWheel"));
     if(scroll != 0){
          UnequipEvent();

          arrayPos = (arrayPos+scroll)%weapons.Count;

          EquipEvent();
     }
}

The advantage of these methods is not only more compact code but also the fact that Input.GetAxis only gets evaluated once per frame, saving another lookup. The modulo operator is also slightly faster than using if statements, although that isn’t a speedup you will probably notice.