Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why does my script clone a Handle into every part?

local click = script.Parent.ClickDetector
local Number = 1

click.MouseClick:Connect(function(clicked)
	Number = 1
	local rand = math.random(1, 512)
	for _, v in pairs(workspace.Mine:GetDescendants()) do
		if v.Name == ("Handle") then
			v:Destroy()
		end
		if v:IsA("Part") then
			if Number == rand then
				local Clone = game.ServerStorage.Handle:Clone()
				Clone.Parent = workspace
				Clone.Position = v.Position
			else
				Number = Number + 1
			end
		end
	end
end)

For some reason this clones in every part, not just one.

1 comment

0

i assume its because your doing it on a loop. what youve done is get every part from the workspace, and check if it is a part. If it is, then it clones to every part that is a part. Sorry if thats wrong, i dont understand lua too much.

1 answer

The main problem with this is that you are using a loop to first remove anything named "handle" then afterwards are just cloning a handle into anything that is a "Part" by its Position. If you want the script to add the new Handle to a specific part, you will have to define the name of v in the function to do so (as v represents all objects in the workspace).

If you only wanted one handle to be cloned, you'd have to add a line designating that if there is a handle, then to either return end (much like a debounce) or just not perform the clone, such as:

local click = script.Parent.ClickDetector
local Number = 1

click.MouseClick:Connect(function(clicked)
Number = 1
local rand = math.random(1, 512)
	for _, v in pairs(workspace.Mine:GetDescendants()) do
		if v.Name == "Handle" then
			v:Destroy()
		elseif v:IsA("Part") and v.Name ~= "Handle" then
			local check = workspace:FindFirstChild("Handle")
			if Number == rand and check == nil then
				local Clone = game.ServerStorage.Handle:Clone()
				Clone.Parent = workspace
				Clone.Position = v.Position
				break
			else
				Number = Number + 1
			end
		end
	end
end)

Edits: Moved a redundant if-then you didnt need, added a check, used break to stop the for loop.

This discussion is preserved as it was. New answers, comments, and votes are closed.