So basically I have this LocalScript at the StarterPack that has a function that is activated when the player clicks on a Part, as soon as the function is active, it creates a clone of a Part located in the workspace and reposition it.
local Player = game:GetService("Players").LocalPlayer local Mouse = Player:GetMouse() local UIS = game:GetService("UserInputService") local RS = game:GetService("RunService") local Part = game.Workspace.Part Mouse.Button1Down:Connect(function() local mPos = UIS:GetMouseLocation() local Target = Mouse.Target if Target == Part then local clone = Part:Clone() clone.Parent = game.Workspace clone.Anchored = true clone.Position = Vector3.new (-2, 7, -2) end end)
The script is working perfectly fine, but I would like to implement one thing, if there was already a clone of that part in that same position then instead of cloning it again I wanted the cloned Part to be destroyed. I'm new to scripting and I know I should try doing something easier, but it is an important part of the game.
You can save the cloned Part as a variable's value so that if that variable has a value (the cloned part) it will destroy it then replace the value to nil or false.
--excluded some variables because they are irrelevant to the question also pay attention to the changes, this script is your script modified. local Player = game:GetService("Players").LocalPlayer local Mouse = Player:GetMouse() local Part = game.Workspace.Part local Clone = nil; Mouse.Button1Down:Connect(function() --local mPos = UIS:GetMouseLocation() local Target = Mouse.Target if Target == Part and not Clone then local clone = Part:Clone() clone.Parent = game.Workspace clone.Anchored = true clone.Position = Vector3.new (-2, 7, -2) Clone = clone; elseif Clone then Clone:Destroy(); Clone = nil; end end)
Note: This only works for one instance. For multiple instances, a table is needed.