Trouble with gun system

I’m making a gun system from the ground up for my third person shooter game. I’m trying to make it shoot continuously when i hold down mouse1, however. For some reason the userinput service goes by way to fast when i hold it, somehow inputting more shots than there are bullets in the chamber. is there a way to delay shots? would i do that on the local script or in the server script? and would it be as simple as putting a wait() somewhere? (also happy late valentines day)
This is the local script that fires the server when the mouse1 button is held.

local replicatedstorage = game.ReplicatedStorage
local player = game.Players.LocalPlayer
local playermouse = player:GetMouse()
local userinput = game:GetService("UserInputService")
local held = false

userinput.InputBegan:Connect(function(input)
	local char = player.Character or player.CharacterAdded:Wait()
	local tool = player.Character:FindFirstChildOfClass("Tool")
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		held = true
		while held == true do
			if tool.Parent == player.Character then
				replicatedstorage.Shoot:FireServer(playermouse.Target)
			end
			game:GetService("RunService").RenderStepped:Wait()
		end
	end
end)

userinput.InputEnded:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		held = false
	end
end)

if you want a cooldown for your shots, you can put a wait(cooldown time you want) like so:

if tool.Parent == player.Character then
replicatedstorage.Shoot:FireServer(playermouse.Target)
wait(cooldown time)
end

i do have a rate of fire as a custom attribute given to the gun tool, however the server script deals with it, ill try to put that attribute into the wait time but im not sure if that will be the safest thing for the game, ill try it anyway.

it works, but however when i spam click it seems to still do more inputs and im not entirley sure why

that is because the placement of the wait method makes the cooldown not spam proof.
if you want to make it spam proof, you will need to give another attribute to the gun and do this:

while held == true do
    if gun:GetAttribute("that attribute") == true then
		if tool.Parent == player.Character then
			replicatedstorage.Shoot:FireServer(playermouse.Target)
		end
        gun:SetAttribute("that attribute", false)
        wait(cooldown_time)
        gun:SetAttribute("that attribute", true)
	end
	game:GetService("RunService").RenderStepped:Wait()
end

also i wanted to ask, how do you paste these scripts so the spaces dont mess up?

highlight the code u want to format and then press the gear and press preformatted text

1 Like

i just realized the problem i did something similar to this instead making a debounce thanks for the help

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.