Raycast fires multiple times every time a tool is equipped and unequipped

So I want to make it where the player can click on a part and have a raycast detect it and take some of its health. Problem is, every time the tool is unequipped and then reequipped, the raycast fires multiple times.
I have tried to solve it multiple times and gone through multiple searches yet I still cannot solve this.

Here is the code

local pickaxe = script.Parent
local rayOrigin = script.Parent.Handle
wait(1)
local mine = script.Parent.Mine
local mineR15 = script.Parent.MineR15
local player = game.Players.LocalPlayer
local character = player.Character
local humanoid = character.Humanoid
local mouse = player:GetMouse()
local minetrack
if humanoid.RigType == Enum.HumanoidRigType.R6 then
	minetrack = humanoid:LoadAnimation(mine)
else
	minetrack = humanoid:LoadAnimation(mineR15)
end

local repStorage = game:GetService("ReplicatedStorage")

pickaxe.Equipped:Connect(function()
	pickaxe.Enabled = true
	local mousePos = mouse.Hit.p
	local direction = (mousePos-rayOrigin.Position).Unit * 25
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {character}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local result = workspace:Raycast(rayOrigin.Position, direction,raycastParams)
	mouse.Button1Down:Connect(function()
		if pickaxe.Enabled then
			minetrack:Play()
			if result then
				print(result.Instance.Name)
				if result.Instance.Name == "Rock" then
					result.Instance.Parent.Health.Value -= 1
					if result.Instance.Parent.Health.Value == 0 then
						repStorage.CloneTool:FireServer(result.Instance.Parent)
						result.Instance.Parent:Destroy()
					end
				else
					
				end
			end
		else
			result = nil
		end
	end)
end)
pickaxe.Unequipped:Connect(function()
	pickaxe.Enabled = false
end)

If you have a suggestion or an answer that would be very helpful, even a link to a related article would be helpful.

2 Likes

I searched this, and found a similar problem.

I solved it, all I had to do was make the raycast happen in a script and not a local script. Thanks for your help though!

1 Like