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

Trying to do a key collecting game. How do i optimize this script?

Asked by 4 years ago
Edited 4 years ago

game.Workspace.key1.ClickDetector.MouseClick:Connect(function() game.Workspace.key1.Parent = game.ReplicatedStorage end)

game.Workspace.key2.ClickDetector.MouseClick:Connect(function() game.Workspace.key2.Parent = game.ReplicatedStorage end)

game.Workspace.key3.ClickDetector.MouseClick:Connect(function() game.Workspace.key3.Parent = game.ReplicatedStorage end)

game.Workspace.key4.ClickDetector.MouseClick:Connect(function() game.Workspace.key4.Parent = game.ReplicatedStorage end)

game.Workspace.key5.ClickDetector.MouseClick:Connect(function() game.Workspace.key5.Parent = game.ReplicatedStorage end)

1 answer

Log in to vote
2
Answered by
ACHRONlX 255 Moderation Voter
4 years ago

You can use a table to store all the keys. Then loop through them;

local ToClick = {workspace.key1, workspace.key2, workspace.key3, workspace.key4);

for i, Key in pairs(ToClick) do
    Key.ClickDetector.MouseClick:Connect(function(Player)
          Key.Parent = game.ReplicatedStorage;
    end)
end
0
Thank you Zethuslmam. i wanted to ask, what does "in pairs" do? mattking71 29 — 4y
0
I'm pretty sure in pairs just returns 2 values from every iteration of that loop, i being the index (for example if the loop was iterating through workspace.key1, i would be 1 since that's the first value in the table) and the actual value from that table (if the index was 1 then that means we are at the first position of the table so the variable "Key" would be workspace.key1) PhantomBrix 40 — 4y
Ad

Answer this question