Check if a player is next to a dummy through table using a loop

Hello, I’m working on a dialogue system, i’m stuck on a little issue. i want to display a ui when the player is next to a dummy. i made a table through a folder where are npc which is possible to talk to them.

i use a loop but it’s work for one npc i have tried multiple solution but nothing work

--check if the player is next to a dummy

game:GetService("RunService").Heartbeat:Connect(function()
	for i, v in pairs(dialogueSystem.NPCFolder:GetChildren()) do
		local dist = (game.Players.LocalPlayer.Character.PrimaryPart.Position - v.PrimaryPart.Position).Magnitude
		if dist <= dialogueSystem.maxDistance then
			game.Players.LocalPlayer.PlayerGui.GuiHandler.Interact.Visible = true
		elseif dist > dialogueSystem.maxDistance then
			game.Players.LocalPlayer.PlayerGui.GuiHandler.Interact.Visible = false
		end
	end

end)
-- make the table
function dialog:getNPC()
	local folder = self.NPCFolder:GetChildren()
	local npcTable = {}
	for i, npc in pairs(folder) do
		npcTable[npc.Name] = npc
	end
	return npcTable
end

i hope someone can help me to find a solution for this issue

Based on the code you provided, it seems that you are checking the distance between the player and each NPC in the dialogueSystem.NPCFolder folder. However, you are setting the visibility of the interact UI based on the distance to each NPC individually, which might cause issues if there are multiple NPCs nearby.

To fix this, you can modify your code to only set the visibility of the interact UI to true if the player is near any NPC. Here’s an updated version of your code:

local player = game.Players.LocalPlayer
local maxDistance = dialogueSystem.maxDistance
local interactUI = player.PlayerGui.GuiHandler.Interact

game:GetService("RunService").Heartbeat:Connect(function()
	local nearNPC = false
	for _, npc in pairs(dialogueSystem.NPCFolder:GetChildren()) do
		local dist = (player.Character.PrimaryPart.Position - npc.PrimaryPart.Position).Magnitude
		if dist <= maxDistance then
			nearNPC = true
			break -- Exit the loop once we find a nearby NPC
		end
	end

	interactUI.Visible = nearNPC
end)

In this updated code, we introduce a boolean variable nearNPC that is initially set to false. Inside the loop, if the player is near any NPC, we set nearNPC to true and immediately exit the loop using break. After the loop, we set the visibility of the interact UI based on the value of nearNPC.

This way, the interact UI will be visible only when the player is near at least one NPC from the dialogueSystem.NPCFolder.

Make sure to replace dialogueSystem.NPCFolder with the actual reference to your folder containing the NPCs. Also, ensure that the GuiHandler.Interact element exists in the PlayerGui and has the appropriate visibility settings.

thanks you for helping me it’s working perfectly

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