Home > Software design >  Pick up weapons and equipping them, if weapon limit reached, replace our weapon
Pick up weapons and equipping them, if weapon limit reached, replace our weapon

Time:05-16

I have a weapon switching system that is very simple, I have a list of weapons and I can cycle through them using my scroll wheel

    int previousSelectedWeapon = selectedWeapon;

    if(Input.GetAxis("Mouse ScrollWheel") > 0f)
    {
        if(selectedWeapon - 1 >= 0)
        {
            selectedWeapon--;
        }
        else
        {
            selectedWeapon = maxWeapons;
        }
    }

    if(Input.GetAxis("Mouse ScrollWheel") < 0f)
    {
        if(selectedWeapon   1 <= maxWeapons)
        {
            selectedWeapon  ;
        }
        else
        {
            selectedWeapon = 0;
        }
    }

    if(previousSelectedWeapon != selectedWeapon)
    {
        SelectWeapon();
    }
}

public void SelectWeapon()
{
    int i = 0;

    foreach (Transform weapon in transform)
    {
        if (i ==  selectedWeapon)
        {
            weapon.gameObject.SetActive(true);
        }
        else
        {
            weapon.gameObject.SetActive(false);
        }
        i  ;
    }
}

However this is not exactly what I'm looking for, I want to be able to have a maximum of x weapons currently equipped and I can only cycle through them.

Let's say I have 1 weapon I can pick up another weapon, but if I have the max amount of weapons equipped, I want my currently selected weapon to be replaced by the weapon I'm picking up

CodePudding user response:

Change just maxWeapon to weapon.Count if it's a List or weapon.Length if it's a array; Add new weapon to list, and set selected as a last element of list?

CodePudding user response:

To solve this problem, I fixed this code completely. Put only the content inside the code in the class. The bottom system works like switching weapons in GTA. If you want the list rotation to be locked, leave a comment again.

public class WeaponSelect : MonoBehaviour
{
    [SerializeField]
    private int selectedWeapon = 0;
    private void Update()
    {
        var deltaY = Input.GetAxisRaw("Mouse ScrollWheel");

        if (deltaY == 0) return;

        if (deltaY > 0) selectedWeapon =   selectedWeapon % transform.childCount;

        if (deltaY < 0) selectedWeapon = selectedWeapon == 0 ? transform.childCount-1 : --selectedWeapon;

        SelectWeapon(selectedWeapon);
    }

    public void SelectWeapon(int index)
    {
        foreach (Transform weapon in transform) weapon.gameObject.SetActive(false);

        transform.GetChild(index).gameObject.SetActive(true);
    }
}
  • Related