Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why does my script clone a Handle into every part?

Asked by
Joshument 110
5 years ago
Edited 5 years ago
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.

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. jdm4llfem8 94 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

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.

Ad

Answer this question