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

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

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

✓ Accepted answer

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

2 comments

0

Thank you Zethuslmam. i wanted to ask, what does "in pairs" do?

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)

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