So I made a script where if a player touches the part, a gui appears and I tried to do it the other way around if the player leaves the part, the gui starts to disappear. Everything works but if I leave the part, the gui keeps showing up.
local part = script.Parent
local bool = part.On
part.Touched:Connect(function(hit)
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if plr then
while true do
plr.PlayerGui.Sectors.S1.Image.ImageTransparency = plr.PlayerGui.Sectors.S1.Image.ImageTransparency - 0.1
plr.PlayerGui.Sectors.S1.SubTitle.TextTransparency = plr.PlayerGui.Sectors.S1.SubTitle.TextTransparency - 0.1
plr.PlayerGui.Sectors.S1.Title.TextTransparency = plr.PlayerGui.Sectors.S1.Title.TextTransparency - 0.1
wait(0.1)
end
end
end)
part.TouchEnded:Connect(function(hit)
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if plr then
while true do
plr.PlayerGui.Sectors.S1.Image.ImageTransparency = plr.PlayerGui.Sectors.S1.Image.ImageTransparency + 0.1
plr.PlayerGui.Sectors.S1.SubTitle.TextTransparency = plr.PlayerGui.Sectors.S1.SubTitle.TextTransparency + 0.1
plr.PlayerGui.Sectors.S1.Title.TextTransparency = plr.PlayerGui.Sectors.S1.Title.TextTransparency + 0.1
wait(0.1)
end
end
end)
Alternatively you could use a for loop, which is very slightly more efficient than using tween service (when it comes to singal properties, like this use case). Try this:
First, replace this while loop:
Now, where that while loop was, add a for loop like this:
for i=0,1,0.1 do
plr.PlayerGui.Sectors.S1.Image.ImageTransparency = plr.PlayerGui.Sectors.S1.Image.ImageTransparency + 0.1
plr.PlayerGui.Sectors.S1.SubTitle.TextTransparency = plr.PlayerGui.Sectors.S1.SubTitle.TextTransparency + 0.1
plr.PlayerGui.Sectors.S1.Title.TextTransparency = plr.PlayerGui.Sectors.S1.Title.TextTransparency + 0.1
task.wait(0.1)
end
Using a for loop is actually worse. I tried using a rainbow color part script with a for loop and without one. The results were 6% CPU usage with for loop and 1% with tweens.
I’ve only ever benchmarked changing part transparency (comparing tween to for loops i mean) and the for loop was if I remember about 0.002 seconds faster. However it stops the thread, unlike a tween. So for this maybe you should use a tween or spawn a new thread.
I am using Processing power instead of time taken as a metric here since it doesn’t matter if a script takes 0.02 seconds to change transparency, but it does matter when you have 5% more CPU usage.