Can't figure out

I have a folder with parts in it.

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?

3 Likes

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.

1 Like

That is perfect!

Thank you for helping me solve the problem.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.