I’m currently learning to do some basic scripting with the for loop. I’m trying to make a part’s transparency slowly fade to 1, which works, but trying to make it return in the same motion to 0 transparency isn’t working. Here is the script.
Note: I could probably use TweeningService but I would first wanna learn how to do it with this method
local ClickDetector = script.Parent.ClickDetector
local isPressed = false
ClickDetector.MouseClick:Connect(function()
if not isPressed then
isPressed = true
for i = 0, 1, 0.01 do
script.Parent.Transparency = i
wait()
end
if script.Parent.Transparency == 1 then --this doesn't work
for i = 1,0, 0.01 do
script.Parent.Transparency = i
wait()
end
end
isPressed = false
end
end)
If you’re using a for loop just change the “i” to “-i” in the script.Parent.Transparency = i" Line and keep the for loop the same (do for i = 0, 1, 0.01 do for both), see if that works .
In order to reverse the for loop, the increment value 0.01 should be negative, meaning -0.01, since technically going from 1 to 0 needs going backwards, in other words subtraction. Generally, in
for i = x, y, z
if x is greater than y, z needs to be negative.
The value of the transparency property is in the range (0, 1), so it can go from 0 to 1, meaning it can’t be negative, else it’s just interpreted as a 0. Something else you can do within the same mindset as your idea, doing 1-i instead of i.
you don’t have to check if it’s transparent, as it’d be transparent then already so it’d be, but that’s just to clean the script.
and the second for loop’s increment needs to be negative, because what it’s doing is adding .01 infinitely to 1, so you’d need to change it to -.01
local ClickDetector = script.Parent.ClickDetector
local isPressed = false
ClickDetector.MouseClick:Connect(function()
if not isPressed then
isPressed = true
for i = 0, 1, .01 do
script.Parent.Transparency = i
wait()
end
for i = 1,0, -.01 do
script.Parent.Transparency = i
wait()
end
end
isPressed = false
end)