My gun is shooting while not being equipped

I was working on a gun when I realized that you could shoot the gun and do damage even while the gun was unequipped.


Here’s the code:

script.Parent.Fire.OnServerEvent:Connect(function(player, mousePos)
	if not debounce then
		script.Parent.Settings.Ammo.Value = script.Parent.Settings.Ammo.Value - 1
		local raycastParams = RaycastParams.new()
		raycastParams.FilterDescendantsInstances = {player.Character}
		raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
		local raycastResults = workspace:Raycast(script.Parent.Handle.Position, (mousePos - script.Parent.Handle.Position)*300,raycastParams)
		local ray = Ray.new(script.Parent.Handle.CFrame.p,(mousePos - script.Parent.Handle.CFrame.p).unit * 300)
		local hit, position = workspace:FindPartOnRay(ray, script.Parent.Parent)
		local distance = (position - script.Parent.Handle.CFrame.p).magnitude
		local part = Instance.new("Part")
		part.Anchored = true
		part.CanCollide = false
		part.Transparency = 0
		part.BrickColor = BrickColor.new("Gold")
		part.Size = Vector3.new(0.2, 0.2, distance)
		part.CFrame = CFrame.new(position, script.Parent.Handle.BulletPosition.WorldCFrame.p) * CFrame.new(0, 0, -distance / 2)
		part.Parent = workspace
		game.Debris:AddItem(part, 0.1)
		if raycastResults then
			local hitPart = raycastResults.Instance
			local model = hitPart:FindFirstAncestorOfClass("Model")
			if model then
				if model:FindFirstChild("Humanoid") then
					model.Humanoid.Health -= 30
				end
			end
		end
	end
end)
1 Like

Do another if checking if the player has the tool equipped. You can do this by:

if player.Character:FindFirstChild("Tool") then
--Add tool's name inside of the " "
2 Likes

Something I like to do is create a variable to see if it is equipped.

--local script
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local enabled = false
local tool = script.Parent

tool.Equipped:Connect(function()
    enabled = true
end)

tool.Unequipped:Connect(function()
    enabled = false
end)

mouse.Button1Down:Connect(function()
    if enabled == true then
       --Insert code here.
    end
end)

That’s just how I do it. Just check if the tool is equipped or not.

1 Like