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

Generic For Loop Not Destroy Part?

Asked by 5 years ago

I'm new to generic for loops, and for that matter, fairly new to scripting in general.

I made this click detector that if touched, creates 5 parts and then waits 3 seconds and destroys them. I don't need this for a game of mine, but am simply using it so that when the time comes to use generic for loops, I have experience with them.

Here is my code:

local clickdetector = script.Parent:WaitForChild("ClickDetector")

clickdetector.MouseClick:connect(function()
    for i = 1,5,1 do
        local part = Instance.new("Part",game.Workspace)
    end
end)

for i,part in pairs(game.Workspace:GetChildren()) do
    if part.Name == 'part' then
        wait(3)
        part:Destroy()
    end
end

When I play the game no errors print in the output. I don't understand what I'm doing wrong. If you can please help me thank you, and even if you can't thank you for your time.

1 answer

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

To start off, make sure you use workspace and not game.Workspace since workspace is quicker, cleaner, and easier to read.

And the reason why there are no errors is because your second for loop is looking for an instance named "part", but that does not exist because you did not define the variable "part" a name in your first loop, so it defaulted to "Part", your if-statement is looking for a lowercase "part". You should also have that second for loop inside of the event.

local clickdetector = script.Parent:WaitForChild("ClickDetector")

clickdetector.MouseClick:connect(function()
    for i = 1,5,1 do
          local part = Instance.new("Part",workspace)
        part.Name = 'part'
    end

    for i,part in pairs(workspace:GetChildren()) do
      if part.Name == 'part' then
            wait(3)
            part:Destroy()
     end
    end
end)
0
You could just make the if-statement search for an uppercase "Part" instead, but I was just trying to show you why exactly this did not work. jackfrost178 242 — 5y
0
It is game.workspace that is deprecated not game.Workspace User#5423 17 — 5y
0
Edited jackfrost178 242 — 5y
Ad

Answer this question