I am new to coding, and decided to use an tutorial to make an simple gun system. The code has been changed to my liking but I have an problem. When ever I reload the gun stops shooting. I don’t know what’s wrong with it.
Here’s the code for the gun:
local gun = script.Parent
local re = script.Parent:WaitForChild("RemoteEvent")
local player = nil
local mouse = nil
local connection = nil
local kickBack = script.Parent:WaitForChild("Kickback")
local kickTrack = nil
local canShoot = true
local coolDown = .5
local rs = game:GetService("ReplicatedStorage")
local gunScreenGuiTemplate = script.Parent:WaitForChild("GunScreenGui")
local gunScreenGui = nil
local ammoLbl = nil
local ammo = 6
local maxAmmo = 6
local click = script.Parent.pistol:WaitForChild("Click")
local reloadSnd = script.Parent.pistol:WaitForChild("Reload")
local isReloading = false
local uis = game:GetService("UserInputService")
local reloadKey = Enum.KeyCode.R
local reloadAnim = gun:WaitForChild("Reload")
local reloadTrack = nil
local function reload()
local ammo = 0
isReloading = true
reloadSnd:Play()
reloadTrack:Play()
wait(reloadTrack.Length)
ammo = maxAmmo
ammoLbl.Text = "Ammo: " .. ammo .. "/" .. maxAmmo
isReloading = false
end
local function makeAmmoGui()
local playerGui = player:WaitForChild("PlayerGui")
gunScreenGui = playerGui:FindFirstChild("GunScreenGui")
if not gunScreenGui then
gunScreenGui = gunScreenGuiTemplate:Clone()
gunScreenGui.Parent = playerGui
end
gunScreenGui.Enabled = true
ammoLbl = gunScreenGui:FindFirstChild("AmmoLbl")
ammoLbl.Text = "Ammo: " .. ammo .. "/" .. maxAmmo
end
local function onActivated()
if canShoot and ammo > 0 then
canShoot = false
kickTrack:Play()
re:FireServer(mouse.Target)
ammo -= 1
ammoLbl.Text = "Ammo: " .. ammo .. "/" .. maxAmmo
wait(coolDown)
canShoot = true
elseif ammo <= 0 and not isReloading then
--click:Play()
reload()
end
end
local function onEquipped()
player = game.Players.LocalPlayer
mouse = player:GetMouse()
connection = gun.Activated:Connect(onActivated)
local char = player.Character or player.CharacterAdded:Wait()
local hum = char:WaitForChild("Humanoid")
kickTrack = hum.Animator:LoadAnimation(kickBack)
reloadTrack = hum.Animator:LoadAnimation(reloadAnim)
makeAmmoGui()
end
local function onUnequipped()
player = nil
mouse = nil
connection:Disconnect()
if gunScreenGui then
gunScreenGui.Enabled = false
end
end
gun.Equipped:Connect(onEquipped)
gun.Unequipped:Connect(onUnequipped)
uis.InputBegan:Connect(function(input, gameProcessFlg)
if input.KeyCode == reloadKey and ammo ~= maxAmmo and not isReloading then
reload()
end
end)
Any help or suggestion’s will be helpful for me.