Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

If I unequip and equip my weapon back, ammo substracts multiple times, why?

So, i've been doing a zombie game nowadays, and i have a gun, which if I have at the first moment of the game, so it spawns with me, it works perfectly. But if I unequip it and equip it back then instead of 1 bullet, it substracts 2 bullet, then 3, then 4, 5 , 6, 7, and so on. How do I fix this? Thanks!

local maxammo = 10
local ammo = maxammo
local reloading = false
local plr = game.Players.LocalPlayer
local plrgui = plr:WaitForChild("PlayerGui")
local text = plrgui:WaitForChild("Ammo"):FindFirstChild("AmmoCount")

script.Parent.Equipped:Connect(function(Mouse)
	text.Text = (ammo).." / "..maxammo
	local function reload()
		reloading = true
		wait(1)
		script.Parent.reloadingsound:Play() 
		ammo = maxammo
		reloading = false
	end

	script.Parent.Activated:Connect(function()
		if ammo > 0 and not reloading then
			ammo = ammo - 1
			script.Parent.gunshot:Play()
			if Mouse.Target.Parent:FindFirstChild("Humanoid") then
				script.Parent.DealDamage:FireServer(Mouse.Target.Parent, 25)
			end
		elseif reloading == false then
			reload()
			script.Parent.gunshot:Stop()
		end

		while wait() do
			text.Text = (ammo).." / "..maxammo
		end
	end)

	local input = game:GetService("UserInputService")
	input.InputBegan:Connect(function(Key)
		if Key.KeyCode == Enum.KeyCode.R and reloading == false and ammo ~= maxammo then
			reload()
		end
	end)
end)

1 answer

It's because everytime you equip your weapon you create a new connection to script.Parent.Activated

1 comment

0

And how can I prevent it from doing that?

This discussion is preserved as it was. New answers, comments, and votes are closed.