I am currently trying to write a sort of dynamic fog system, when a player touches a part within a specific folder, it triggers the code below and plays a tween that changes the FogEnd.
The script works just fine, except for one issue. The script loops through every region, however when it finds one region that meets the criteria, it keeps looping through the other regions that don’t. This causes an issue later on in the script, as it plays a tween that is only supposed to play when leaving a region that meets said criteria.
I am unsure how to fix this, as I am trying to keep the code as optimized as possible (at least for my skill level) and I can’t find a reliable way to detect when the player has left a region without looping through every single region and causing the tween to go off.
-- Variables
local WS = game:GetService("Workspace")
local Regions = WS:WaitForChild("LightingChanges")
local overlapParams = OverlapParams.new()
local MIN = 60
local TweenService = game:GetService("TweenService")
local lighting = game:GetService("Lighting")
local found = false
-- Main loop
while task.wait(1) do
for i, v in pairs(Regions:GetChildren()) do -- looping through the regions
found = false
task.wait()
if game.Players.LocalPlayer.Character then
overlapParams.FilterDescendantsInstances = game.Players.LocalPlayer.Character:GetDescendants()
overlapParams.FilterType = Enum.RaycastFilterType.Whitelist
local parts = WS:GetPartsInPart(v, overlapParams)
for _, part in pairs(parts) do -- looping through the parts detected in the region
if part:FindFirstAncestor(game.Players.LocalPlayer.Name) then
found = true
break
else
found = false
end
end
if found == true then -- after the player model has been found, checking the "found" criteria
local FogADD = v:GetAttribute("FogChange")
local FogIninfo = TweenInfo.new(0.125, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, false, 0)
local FogInTween = TweenService:Create(lighting, FogIninfo, {FogEnd = (FogADD)})
if lighting.FogEnd ~= FogADD then -- checking the lighting criteria
if FogADD < MIN then
if game.Players.LocalPlayer.Character:FindFirstChildOfClass("Tool") then
FogInTween = TweenService:Create(lighting, FogIninfo, {FogEnd = (MIN)})
FogInTween:Play()
break
end
end
FogInTween:Play()
end
else -- Where the script begins to fail; when looping through the other regions the script finds that equipped = false, and thus causes the tween to go off every second.
if game.Players.LocalPlayer.Character:FindFirstChildOfClass("Tool") then
MIN = 60
else
MIN = 18
end
local FogOutinfo = TweenInfo.new(0.125, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, false, 0)
local FogOutTween = TweenService:Create(lighting, FogOutinfo, {FogEnd = (MIN)})
FogOutTween:Play()
end
else
return
end
end
end