script.Parent.Parent.Equipped:Connect(function(mouse) mouse.Button1Down:Connect(function() if mouse.Hit == nil then return end local raycast = Ray.new(script.Parent.Position, mouse.Hit) workspace:FindPartOnRay(raycast):Destroy() end) end)
You can't just dump your code here and expect us to know the problem with it. You should always give context to your situation, by stating:
Right off the bat, I see numerous problems with your code, which I will address:
Don't nest connections if you're not going to disconnect them: This can lead to multiple connections being made of the inner event, depending on the frequency of the outer event, which all do the same thing which normally causes unintended results and / or memory leaks. You could use a variable to make reference to the connection and then when the tool is equipped, disconnect the connection if it exists, but there is a better option: The Activated event of tools, which fires when the user clicks their left mouse button when the tool is equipped
Ray.new
and workspace:FindPartOnRay
are both deprecated and you should be using the new alternative: Workspace:Raycast (See this page on how to use the new raycast method). You also can't assume that the raycast always hits something, especially when you have the arguments wrong: the 2nd argument is supposed to be relative, so it should've been mouse.Hit - script.Parent.Position
, but we do not need to bother with raycasting, because we can use Mouse.Target
which references the part in the workspace that the mouse is currently hovering over
Mouse.Hit
is a CFrame that describes the current position of the mouse in 3D space and will never be nil: if the mouse is not hovering over anything but the sky, the Hit
property will just be 1000 studs away from the camera's position.
So we will use the Activated event and Mouse.Target as mentioned before. Note that you need to add a check to see if the object the mouse is hovering over is a ball so that the player is unable to delete anything else in the game (maybe have a folder in workspace where the balls will be parented, perhaps it could be named "FallingBalls" or whatever you desire)
Make sure this is a local script or it'll not work
local Mouse = game.Players.LocalPlayer:GetMouse() script.Parent.Activated:Connect(function() if not Mouse.Target or Mouse.Target.Parent.Name ~= "FallingBalls" then return end Mouse.Target:Destroy() end)