I made a script for a lightbulb which works fine and is supposed to fade out when you turn it off and fade in when on. I had no problem using a for loop for when you were to turn off the light but I found that turning on the light wasn’t as simple. I apologize greatly if this may seem like Im trying to ask people to write a system for me but really Im just trying to find a better solution!
par = script.Parent
LightOn = true
par.ClickDetector.MouseClick:Connect(function()
if LightOn then
for i = 1.5,0,-0.25 do
par.Light.Brightness = i
wait(0.01)
end
LightOn = false
else if not LightOn then
par.Light.Brightness = 0.25
wait(0.01)
par.Light.Brightness = 0.50
wait(0.01)
par.Light.Brightness = 0.75
wait(0.01)
par.Light.Brightness = 1
wait(0.01)
par.Light.Brightness = 1.25
wait(0.01)
par.Light.Brightness = 1.50
LightOn = true
end
end
end)``
It might be more sufficient to use tweening to achieve an in/out effect. You could use something like…
local par = script.Parent --//Path to 'par'
local tween_service = game:GetService("TweenService")
local goal1, goal2 = {Brightness = 1.5}, {Brightness = 0}
local duration = 2 --//How long it takes to transition between the two goals
local tween_info = TweenInfo.new(duration, Enum.EasingStyle.Linear)
local tween1, tween2 = tween_service:Create(par.Light, tween_info, goal1), tween_service:Create(par.Light, tween_info, goal2)
tween1.Completed:Connect(function() tween2:Play() end)
tween2.Completed:Connect(function() tween1:Play() end)
tween1:Play()
Not necessarily. If the script is placed in the object itself which is what I presumed, then when that object instance is destroyed it’ll clean up automatically.
And I gotta disagree with you on tweens being inefficient. I’ve actually had people recommend to use tweens over other methods of moving or animating objects. And you’d have to use a while loop any way to run a thread constantly for a case like this, so it really should be no different than to let ROBLOX’s built-in API take care of this for you, most likely, in a more sufficient manner.
Lerping a light is perfect for this case, you do not need a new thread to avoid yields as you need to “wait” until “x” tween finishes to Play another one. You connecting them to a “Completed” event is even worse as it results in creating a new unneeded thread.