"while (blank) do" script repeats after meeting requirement

I’m currently making a light that dims in and out and it keeps counting over the condition that I set.
Here’s the code.

while script.Parent.Transparency ~= 1 do
	wait(.05)
	script.Parent.Transparency = script.Parent.Transparency + .05
end

I don’t know if this is a bug or an error on my end. Any possible ways to bandage the issue?

you may want to replace ~= with < as it will keep running if it’s not 1, meaning any miniscule percentage extra will mean it won’t ever be exactly 1.

The difference here is instead of waiting until it’s exactly 1, it will wait until it’s 1 or more, so any extra bit added on will be fine.

3 Likes

Any time you’re working with decimal points, never assume the number will be exactly what you expect. 0.05 doesn’t actually translate into binary, so it gets rounded. As such, your number will never be exactly 1.

It’s exactly like how 1/3 = 0.33333333 repeating forever. You can write all the 3s you want, but sooner or later you’re going to run out of paper to write on, and you’ll need to round it down and stop repeating. If you add that number to itself, you’ll get 0.999999999 instead of 1. It’s just rounding errors and it can’t be avoided.

Another solution is to use integers. 1/0.05 = 20, so you can do this instead.

local t = 0
while t ~= 20 do
	wait(.05)
    t+=1
	script.Parent.Transparency = t/20
end
4 Likes

What is the issue in the first place?
I noticed that you just have +0.5 so it’s just going to go transparent after a second. I’m not sure if that is the issue though

The likely cause of your problem is that the transparency value isn’t hitting exactly 1 which then causes the loop to keep running. At the moment your checking if the transparency value ~= 1 and not accounting for the possibility that it could go above 1.

Possible fix:

while script.Parent.Transparency >= 1 do
	wait(.05)
	script.Parent.Transparency = script.Parent.Transparency + .05
end

I personally wouldn’t use a while loop to do what your trying to do and instead use TweenService or RunService.Heartbeat.

local TweenService = game:GetService("TweenService")

local tweenInfo = TweenInfo.new(
	1, -- Time
	Enum.EasingStyle.Linear,
	Enum.EasingDirection.Out,
	-1, -- How many times the tween repeats. If set below 0 it will repeat forever
	false -- Reverse
)

local goals = {Transparency = 1}

local tween = TweenService:Create(script.Parent, tweenInfo, goals)
tween:Play()

Also, it’s worth mentioning that wait(n) is deprecated and task.wait(n) should be used instead.