While loop still running when it shouldn't be?

I have a UI that pops up whenever a player levels up and it has a starburst type background that rotates. However when the UI gets removed, it keeps running and thus erroring out?

local function showLevelUp()
	local UIClone = LevelledUp:Clone()
	UIClone.Parent = PlayerGui
	
	spawn(function()
		while UIClone.Starburst do
			for i = 0, 360 do 
				UIClone.Starburst.Rotation = i -- error here
				wait()
			end
			wait()
		end
	end)
	
	wait(3)
	
	if UIClone then
		UIClone:Destroy()
	end
end

Error
[Starburst is not a valid member of ScreenGui]
Figured since I have while UIClone.Starburst do it would only run while the Starburst image is actually there

It would be:

while UIClone:FindFirstChild("Starburst") ~= nil do
...
end

because your trying to index a nil value and it throws instead of returning nil.
Also I recommend having a variable that is changed for when the starburst is deleted rather than check everytime

2 Likes

The problem you were having comes from not checking if UIClone.Starburst exists from inside the for loop. e.g, this would’ve been totally safe:

while UIClone.Starburst do -- might as well be true
	for i = 0, 360 do
		if UIClone.Starburst then
			UIClone.Starburst.Rotation = i
			wait()
		else
			break
		end
	end
	wait() -- not really needed
end

Replace your spawn function with this:

spawn(function()
	local i = 0
	while UIClone.Starburst do
		i = i%360 + 1 -- loops between 1 and 360
		UIClone.Starburst.Rotation = i
		wait()
	end
end)
1 Like