How to stop this loop and when player’s distance far from maximum distance play the loop again
script;
local Doors = script.Parent
local DoorTweenInfo = TweenInfo.new(0.5, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, true, 0)
local LeftDoorOpenTween = TweenService:Create(Doors.LeftDoor, DoorTweenInfo, {CFrame = Doors.LeftDoorOpen.CFrame})
local LeftDoorCloseTween = TweenService:Create(Doors.LeftDoor, DoorTweenInfo, {CFrame = Doors.LeftDoorClose.CFrame})
local RightDoorOpenTween = TweenService:Create(Doors.RightDoor, DoorTweenInfo, {CFrame = Doors.RightDoorOpen.CFrame})
local RightDoorCloseTween = TweenService:Create(Doors.RightDoor, DoorTweenInfo, {CFrame = Doors.RightDoorClose.CFrame})
RightDoorOpenTween:Play()
LeftDoorOpenTween:Play()
local function findPlayer()
local players = game.Players:GetPlayers()
local maxDistance = 10
local nearestTarget
for index, player in pairs(players) do
if player.Character then
local target = player.Character
local distance = (Doors.DoorCenter.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance then
nearestTarget = target
maxDistance = distance
end
end
end
return nearestTarget
end
local function closeTarget(target)
local distance = (Doors.DoorCenter.Position - target.HumanoidRootPart.Position).Magnitude
if distance > 8 then
RightDoorOpenTween:Play()
LeftDoorOpenTween:Play()
else
RightDoorCloseTween:Play()
LeftDoorCloseTween:Play()
end
end
while wait(0.001) do
local target = findPlayer()
if target then
closeTarget(target)
break
end
end