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

Generic For Loop Not Destroy Part?

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

✓ Accepted answer

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)

3 comments

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.

0

It is game.workspace that is deprecated not game.Workspace

0

Edited

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