How can I break this loop

So I’m trying to make a Dummy that slowly becomes visible. What Im trying to do is use a for loop to make each part visible slowly. I want to add a check that breaks the loop whenever the transparency reaches 0, however, I get an error that says “break statement must be inside loop”. This is my script:

		for _, Part in pairs(mystand:GetDescendants()) do
			if Part:IsA("BasePart") then
				RunService.Heartbeat:Connect(function()
					Part.Transparency = Part.Transparency - .1
					if Part.Transparency == 0 then
						break
					end
				end)
			end	
		end

hopefully someone can help!

I’m not sure what code is just outside of the snippet that you shared, but it looks like you’re potentially creating a massive memory leak problem with your Heartbeat connection. I’m assuming your break is meant to disconnect the connection? You would need to store the connection as a variable and disconnect it.

local connection -- create the variable. necessary to disconnect from within the function
connection = RunService.Heartbeat:Connect(function()
    Part.Transparency = Part.Transparency - .1
    if Part.Transparency == 0 then
        connection:Disconnect() -- disconnect function
    end
end)

I’m trying to break out of the for loop. If i disconnect the function, the for loop still continues, therefore restarting the connection.

Set a variable outside of the loop and connection to true and check if it’s false inside the loop.

local DoLoop = true
for _, Part in pairs(mystand:GetDescendants()) do
			if not DoLoop then
				break
			end
			if Part:IsA("BasePart") then
				local Connection
				Connection = RunService.Heartbeat:Connect(function()
					Part.Transparency = Part.Transparency - .1
					if Part.Transparency == 0 then
						Connection:Disconnect()
						DoLoop = false
					end
				end)
			end	
		end

The break statement to finish a loop.This statement breaks the inner loop (for, repeat, or while) that contains it; it cannot be used outside a loop.

You can use return in this case.
A return statement returns occasional results from a function or simply finishes a function.
There is an implicit return at the end of any function, so you do not need to use one if your function ends naturally, without returning any value.

Also, pairs is mostly used for dictionaries, use ipairs for arrays, as GetDescendants() returns an array.