I want to make that If player enters / leave the region, then the fog changes.
What is the issue?
Entering region function is looking fine, but the leaving region function doesn’t run. And maybe another issue is finding player, but there’s no error of that.
What solutions have you tried so far?
I’ve tried using table.find, if else, and checking if there’s no player inside the region.
local R1 = script.Parent.Parent.DarkRegionPart1
local R2 = script.Parent.Parent.DarkRegionPart2
while task.wait() do
local region1 = workspace:GetPartBoundsInBox(R1.CFrame, R1.Size)
for i, regions in pairs(region1) do
local hitlist = {}
if regions.Parent:FindFirstChild("Humanoid") then
local player = game.Players:GetPlayerFromCharacter(regions.Parent)
if regions ~= nil then
table.insert(hitlist, regions.Parent)
regionevent:FireClient(player, true) -- Activate fog
elseif not table.find(hitlist, regions.Parent) then
regionevent:FireClient(player, false) -- Deactivate fog
print("not in region")
end
end
end
end
hi, i tested your code and the hitlist is being reset every iteration of the loop, which means it doesn’t maintain a record of which players were previously in the region
also the check for whether a player has left the region is not correctly implemented, as it’s done within the same loop that detects players entering the region. this won’t detect when a player has left because it doesn’t compare the current state to a previous state.
to fix these problems, you can maintain a list of players currently in the region and update it each iteration of the loop. Only then, you can compare the current list to the previous list to determine which players have entered or left the region
below i leave some example code (your script but fixed)
local regionEvent = script.Parent.Parent.RegionEvent
local R1 = script.Parent.Parent.DarkRegionPart1
local R2 = script.Parent.Parent.DarkRegionPart2
local playersInRegion = {}
while task.wait() do
local region1 = workspace:GetPartBoundsInBox(R1.CFrame, R1.Size)
local currentPlayersInRegion = {}
for _, part in pairs(region1) do
if part.Parent:FindFirstChild("Humanoid") then
local player = game.Players:GetPlayerFromCharacter(part.Parent)
if player then
currentPlayersInRegion[player.UserId] = true
if not playersInRegion[player.UserId] then
regionEvent:FireClient(player, true) -- Activate fog
end
end
end
end
for userId, _ in pairs(playersInRegion) do
if not currentPlayersInRegion[userId] then
local player = game.Players:GetPlayerByUserId(userId)
if player then
regionEvent:FireClient(player, false) -- Deactivate fog
end
end
end
playersInRegion = currentPlayersInRegion
end