Is there any way to improve this part generation script?

Just wondering if there’s a more efficient way to generate 100 parts into the workspace when you click a ScreenGUI button :grinning:

Just beginning scripting so feedback appreciated!

function Part()
Instance.new("Part",workspace)
end

numParts = 0

function clicked()

numParts = 0

while true do
	
	Part()
	
	numParts = numParts + 1
	
	if numParts == 100 then
		
		break
		
	end
	
end

end

script.parent.MouseButton1Click:Connect(clicked)

Avoid using the parent argument with instance.new.

Also this while loop can be changed to a for loop.

1 Like

@Halalaluyafail3 If you reread the thread you posted, it says to avoid using it with parent argument when setting other properties immediately afterwards. If the only property you’re going to set is parent, it’s perfectly fine to use the second argument.

@main post
Instead of using a while loop, you can use a numeric for loop that will automatically add to the variable for you. Example:

for numParts=1,100 do
     Part()
end
1 Like

Code Review exists for this very reason.

I’ll give review nonetheless

  • Use a numeric for loop to do something a set amount of times

  • Use the conditional part of the while loop correctly

local i = 0;

while (i < 10) do
    i = i + 1;
end

Even then you should use a for loop for that, but it’s an example.

the for loop helped a lot instead of using a while loop, and the code is a lot more clean as there isn’t the function checking for if there is 100 parts because thats already being done in the for loop. Thanks!

1 Like