I have a list of gun magazines. How do I find the magazine with the highest bullet count?

I have a class called GunMagazine and in it is the value currentAmmo and maxAmmo.

[System.Serializable]
public class GunMagazine {
    public string magazineID, magazineName;
    public int currentAmmo, maxAmmo;
}

Then in the player’s script there is:

public GunMagazine toReloadWith;
public List<GunMagazine> magazines;

what can I do to where when the player reloads it selects the magazine with the highest bullet count and uses that to reload the gun with?

        public int IndexWithMostAmmo()
        {
            int bestIndexChoice = 0;
            for (int i = 0; i < magazines.Count; i++)
            {
                if (magazines[i].currentAmmo > magazines[bestIndexChoice].currentAmmo) bestIndexChoice = i;
            }
            return bestIndexChoice;
        }

You can do fancier things, like LINQ, but this works fine. Change the conditions to suit your needs. The idea is setup a condition and iterate over everything, then return the ideal index.

1 Like

Well, I suppose you would loop through the magazines list, and check each one, only considering the currentAmmo int, because I would imagine you want to select the one that is most loaded, rather than the one with the largest capacity.

That might look sort of like this (untested) code:

int largestMagIndex = -1, largestMagSize = -1;
for(int i = 0; i < magazines.Count; i++)
{
    if (magazines[i].currentAmmo > largestMagSize)
    {
        largestMagIndex = i;
        largestMagSize = magazines[i].currentAmmo;
    }
}
toReloadWith = largestMagIndex;

EDIT: Ninja’d above :smile:

Each gun in the game only accepts certain types of magazines by looking at the name of each magazine to see if it is the right one. Can you ad another parameter that searches if they have the right name?

Assuming your player script also has the string of what gun is selected, then just compare that to the string in the magazines list, and if the names don’t match, don’t count that one.

Modified version of my (still untested) code:

int largestMagIndex = -1, largestMagSize = -1;
for(int i = 0; i < magazines.Count; i++)
{
    if(currentGunType == magazines[i].magazineName && magazines[i].currentAmmo > largestMagSize)
    {
        largestMagIndex = i;
        largestMagSize = magazines[i].currentAmmo;
    }
}
if(largestMagIndex != -1) // make sure a mag was found, in case player has none
    toReloadWith = largestMagIndex;
else
    Debug.LogWarning("No magazines!"); // probably do something else here...

Gee thanks guys that actually worked.

1 Like