Ammo becomes negative

I made an ammo gui that keeps track of how many bullets you have left it all works fine but the bullets go below zero and become negative how can i make it so that bullets never go below zero?
here is my code

-- Services
local UIS = game:GetService("UserInputService")
-- Variables
local gun = script.Parent
local bullets = gun.Bullets
local MaxBullets = gun.MaxBullets.Value
local clipSize = 30
local player = game.Players.LocalPlayer
local GunGui = player.PlayerGui.GunGui.Bullets
GunGui.Text = tostring(bullets.Value) .. ' / ' .. tostring(MaxBullets)
-- Functions
gun.Equipped:Connect(function()
	player.PlayerGui.GunGui.Bullets.Visible = true
end)
gun.Activated:Connect(function()
	bullets.Value = bullets.Value - 1
end)
local userInput = game:GetService("UserInputService")
local function Reload()
	userInput.InputBegan:Connect(function(input, gameProcessed)
		if not gameProcessed then
			if input.UserInputType == Enum.UserInputType.Keyboard then
				local keycode = input.KeyCode
				if keycode == Enum.KeyCode.R then
					if bullets.Value < clipSize and MaxBullets > 0 then
						gun.Reload:Play()
						gun.Reload.Ended:Wait()
						if MaxBullets - (clipSize - bullets.Value) >= 0 then
							MaxBullets = MaxBullets - (clipSize - bullets.Value)
							bullets.Value = clipSize
						else
							bullets.Value = bullets.Value + MaxBullets
							MaxBullets = 0
							GunGui.Text = tostring(bullets.Value) .. ' / ' .. tostring(MaxBullets)
						end
					end
				end
			end
		end
	end)
end
UIS.InputBegan:Connect(function(key)
	if key.KeyCode == Enum.KeyCode.R then
		Reload()
	end
end)

bullets.Changed:Connect(function()
    GunGui.Text = tostring(bullets.Value) .. ' / ' .. tostring(MaxBullets)
end)

gun.Unequipped:Connect(function()
	player.PlayerGui.GunGui.Bullets.Visible = false
end)
gun.Activated:Connect(function()
    if bullets.Value <= 0 then
        Reload()
    else
	    bullets.Value = bullets.Value - 1
    end
end)

It doesn’t reload when the bullets are zero
But it does prevent the bullets from going below zero
so i guess i can fix that myself thank you for helping me

It should reload when the bullets are at 0 and the player activates the weapon again.

No actually it doesn’t do that but i fixed it by doing this

local function ReloadWithoutPressingR()
	if bullets.Value < clipSize and MaxBullets > 0 then
		gun.Reload:Play()
		gun.Reload.Ended:Wait()
		if MaxBullets - (clipSize - bullets.Value) >= 0 then
			MaxBullets = MaxBullets - (clipSize - bullets.Value)
			bullets.Value = clipSize
		else
			bullets.Value = bullets.Value + MaxBullets
			MaxBullets = 0
			GunGui.Text = tostring(bullets.Value) .. ' / ' .. tostring(MaxBullets)
		end
	end
end

gun.Activated:Connect(function()
	if bullets.Value <= 0 then
		ReloadWithoutPressingR()
	else
		bullets.Value = bullets.Value - 1
	end
end)
1 Like