How to make a proper reloading system

I have been trying my self to make this but it just breaks at some point, but im trying to make this for example:
20/30
20 out of 30 Ammo
And when the user reloads it removes 10 from 30 so it will be
30/20
30 out of 20
It cant exceed MaxAmmo tho

local LeftInMagazine = self.instance.Configuration.AmmoCapacity
			local MaxAmmo = self.instance.Configuration.MaxAmmo
			
			-- Current ammo is: self.ammoInWeaponValue.Value
			-- Ammo capacity is how much is left in the mag like available to use for a reload
			self.ammoInWeaponValue.Value = MaxAmmo.Value

This is just the script that automatically sets the ammo to max but thats not what i want.

You should just take away from the AmmoCapacity as much as “free space” is in the mag until MaxAmmo. So if you have 20/30, you need 10 more in the mag, because 30 - 20 = 10 (MAX - CURRENT = NEEDED). Then you take that 10 from the AmmoCapacity, so 30 - 10 = 20 is left (AmmoCapacity = AmmoCapacity - NEEDED or AmmoCapacity -= NEEDED). But make sure to check if there is enough in the AmmoCapacity for a full reload, and if there isn’t, set the AmmoCapacity to 0 and only add as much back to the mag as there was in the AmmoCapacity.

It will look something like this:

local AmmoNeeded = MaxAmmo.Value - self.ammoInWeaponValue.Value

if self.instance.Configuration.AmmoCapacity >= AmmoNeeded then
	self.ammoInWeaponValue.Value = MaxAmmo.Value
	self.instance.Configuration.AmmoCapacity -= MaxAmmo.Value
else
	self.ammoInWeaponValue.Value += self.instance.Configuration.AmmoCapacity
	self.instance.Configuration.AmmoCapacity = 0
end

If you don’t understand something, feel free to ask.
Hope this helps!

1 Like

It just sets the AmmoCapacity to 0 no matter what. If self.ammoInWeaponValue is like 29 and mag has like 30 left then it just sets the mag to 0 and then the self.ammoInWeaponValue to 30.
I have gotten it to work a bit better but the AmmoCapacity can go to a Minus number:

local LeftInMagazine = self.instance.Configuration.AmmoCapacity
			-- MAX - CURRENT = NEEDED
			
			local MaxAmmo = self.instance.Configuration.MaxAmmo
			local calc = MaxAmmo.Value - self.ammoInWeaponValue.Value
			
			if self.ammoInWeaponValue.Value == 0 then
				if LeftInMagazine.Value <= MaxAmmo.Value then
					self.ammoInWeaponValue.Value = LeftInMagazine.Value
					LeftInMagazine.Value = 0	
				end
			else
				self.ammoInWeaponValue.Value += calc
				self.instance.Configuration.AmmoCapacity.Value -= calc
			end
			
1 Like