A problem with gun reloading system

Hello Devforum, i’m creating my gun system and got stuck here when it came to creating a working reloading system. Refilling the weapon’s magazine is no issue to me, but the real problem is that if there’s not enough ammo to refill a magazine entirely, i have barely any idea how to not make it glitch out. I’m really bad at explaining things so here’s a graph of what im talking about:

I tried figuring out how to do exactly what im talking about and came up with this:

local function reload()
	totalAmmo = script.Parent.Parent.Ammo.Total.Value
	currentAmmo = script.Parent.Parent.Ammo.Mag.Value
	canUse = false
	reloading = true
	script.Parent.ReloadEvent:FireServer()
	wait(script.Parent.Reload.TimeLength)
	if totalAmmo < maxAmmo then
		script.Parent.Parent.Ammo.Mag.Value = script.Parent.Parent.Ammo.Total.Value
		script.Parent.Parent.Ammo.Total.Value = 0
	else
		totalAmmo -= (maxAmmo-currentAmmo)
		script.Parent.Parent.Ammo.Total.Value = totalAmmo
		script.Parent.Parent.Ammo.Mag.Value = maxAmmo
	end
	updateAmmo()
	reloading = false
	canUse = true
end

It seems to be working, however it does not function well in some cases.

The ammo in this clip should be 18/0 after reloading. Instead, it’s 11/0

Does anybody know how do i get it to actually working normally? Because sometimes it just does this.

1 Like

hello!

i think the reason this is happening is because you are only setting the magazine’s ammo to the total amount of ammo that was left, and not accounting for the ammo that was already in the magazine (if that makes any sense).

try doing += instead of just =

1 Like

thanks, this worked, but i need to make it so the maximum amount of ammo in the magazine was under the maxAmmo value, which is 30 in this case. your solution worked here, but it allows the magazine to have the amount of ammo above 30. any idea how do i make it so it left the remaining ammo out of the magazine?

image

To calculate the amount of ammo to transfer from your reserves, begin by calculating how many rounds are needed to fill the mag:

local ammoDeficit = MAX_AMMO - currentAmmo

Next, we can figure out how much ammo we can transfer by choosing the smaller of two values:

  1. The ammo reserve
  2. The ammo deficit
local ammoTransfer = math.min(ammoReserve, ammoDeficit)

This ensures we’re transferring no more than the ammo deficit. If the deficit is more than what’s in the reserve, we just dump what’s left in the reserve.

Altogether:

local ammoTransfer = math.min(ammoReserve, MAX_AMMO - currentAmmo)

Finally, deduct ammoTransfer from ammoReserve, and add ammoTransfer to currentAmmo

1 Like

got it to work properly by modifying the reload calculations to look like this:

	local ammoDeficit = maxAmmo - currentAmmo
	local ammoTransfer = math.min(totalAmmo, ammoDeficit)
	script.Parent.Parent.Ammo.Mag.Value += ammoTransfer
	script.Parent.Parent.Ammo.Total.Value -= ammoTransfer

it seems to be working, thank you for the solution!