I am making a tool that allows the user to place parts wherever their mouse clicked. It worked fine until I added a few lines. I was trying to make the user unable to place parts if they were clicking to far away. So I added this
local posit = round(mouse.Hit.p,4)
local Distance = (posit - Vector3.new(RootPart.Position.X,RootPart.Position.Y,RootPart.Position.Z)).Magnitude
if Distance <= 35 then
This is causing immense lag for some reason. The game even crashes after a while. I don’t know what’s causing it as i don’t see anything looping. Here is the full script
local mouse = player:GetMouse()
local tool = script.Parent
tool.Equipped:Connect(function()
equipped = true
end)
tool.Unequipped:Connect(function()
equipped = false
end)
function round(vector, unit)
return vector - Vector3.new(vector.X%unit, vector.Y%unit, vector.Z%unit)
end
while equipped == true do
mouse.Move:Connect(function()
if player.Character:FindFirstChild("Blocks") then
print("foundsuccesful")
if mouse.Target.ClassName == "Part" then
print("partfound")
local NewBlock = script.PreviewPlace:Clone()
NewBlock.Parent = mouse.Target
game.Workspace.PreviewBlocks:ClearAllChildren()
local RootPart = player.Character.HumanoidRootPart
local posit = round(mouse.Hit.p,4)
local Distance = (posit - Vector3.new(RootPart.Position.X,RootPart.Position.Y,RootPart.Position.Z)).Magnitude
if Distance <= 35 then
NewBlock.Transparency = 1
script.Parent.Activated:Connect(function()
script.Parent.PartPlaced:FireServer(mouse.TargetSurface, mouse.Target)
end)
end
if mouse.TargetSurface == Enum.NormalId.Top then
NewBlock.Parent = workspace.PreviewBlocks
NewBlock.Position = mouse.Target.Position + Vector3.new(0,4,0)
elseif mouse.TargetSurface == Enum.NormalId.Left then
NewBlock.Parent = workspace.PreviewBlocks
NewBlock.Position = mouse.Target.Position + Vector3.new(-4,0,0)
elseif mouse.TargetSurface == Enum.NormalId.Right then
NewBlock.Parent = workspace.PreviewBlocks
NewBlock.Position = mouse.Target.Position + Vector3.new(4,0,0)
elseif mouse.TargetSurface == Enum.NormalId.Bottom then
NewBlock.Parent = workspace.PreviewBlocks
NewBlock.Position = mouse.Target.Position + Vector3.new(0,-4,0)
elseif mouse.TargetSurface == Enum.NormalId.Back then
NewBlock.Parent = workspace.PreviewBlocks
NewBlock.Position = mouse.Target.Position + Vector3.new(0,0,4)
elseif mouse.TargetSurface == Enum.NormalId.Front then
NewBlock.Parent = workspace.PreviewBlocks
NewBlock.Position = mouse.Target.Position + Vector3.new(0,0,-4)
end
end
end
end)
end
script.Parent.Unequipped:Connect(function()
game.Workspace.PreviewBlocks:ClearAllChildren()
player.Character.Blocks:ClearAllChildren()
end)
The entire game lags just by having this tool exist in a players inventory. When I make a seperate tool and remove the distance checking, and move the one that does into serverstorage, the lag goes away completely.
The script is probably very messy because I was trying to scrub at everything to see what was causing the lag. Any help is appreciated.