I want to alert the player when they are near one of the parts.
This is what I have. The problem is that it resets alert to false each time it finds a part the player is NOT close to.
local alert
while task.wait(0.1) do
for _, part in pairs(warnings:GetChildren()) do
if part then
local distance = player:DistanceFromCharacter(part.Position)
if distance <= 60 then
alert = true
else
alert = false
end
end
end
end
I don’t want to have a bunch of while loops running inside each part. I just want one while loop for all parts.
Does anyone know how to make it trigger the alert for the part the player is 60 studs away from?
You can refactor this code piece by defaulting alert to false and only setting it to true if the player is near a part.
while task.wait(0.1) do
local alert = false -- sets the default value for alert when ever the loop starts
-- Loops through all of the parts and sets the variable to true if the player
-- is near a part
for _, part in pairs(warnings:GetChildren()) do
if part then
local distance = player:DistanceFromCharacter(part.Position)
if distance <= 60 then
alert = true
end
end
end
if alert == true then
-- do something
end
end
It might be a bit difficult to understand but if we never set alert to false when its checking for parts, it will always stay false, and it will only turn to true if the player is near one or more parts.