I've heard on numerous occasions that using while true do
loops are bad, so how can I replace this script?
if script.Parent.TotalAmmo.Value <= 0 then while true do wait(999999999) end end
while true do
loops aren't necessarily bad, and are actually very commonly used among other programming languages.
However, one thing to note is that in Roblox, you must include a wait()
inside non-terminating loops or your game will freeze (known as a hang). This is due to Roblox's task scheduler and how it invokes every function in succession, and if a function doesn't return or doesn't include some kind of yielding (like wait
), it won't be able to make a full loop. And thus, cannot render the next frame until it does [which is never].
One alternative to a while true do
infinite loop is the RenderStepped function:
game:GetService("RunService").RenderStepped:Connect(function() print(workspace.Part.CFrame.LookVector) --it will print the direction "Part" is pointing every tick end)
This is a good alternative when trying to constantly check for certain values and update other values throughout the time that the game is running.