Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 1 year ago

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

Log in to vote
1
Answered by 1 year ago

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

0
And how can I prevent it from doing that? Kisferenc 47 — 1y
Ad

Answer this question