Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Detecting NPCS only detects the last npc in folder?

local Player = game.Players.LocalPlayer
local NPCS = game.Workspace:WaitForChild("NPCs")
local UIS = game:GetService("UserInputService")
local DetectedNPC = nil

UIS.InputBegan:Connect(function(key)
	if key.KeyCode == Enum.KeyCode.E then
		print("Pressed E")
		if DetectedNPC then
			print("Pressed E with npc nearby")
			game.Workspace.Events.DisableNPC:FireServer(DetectedNPC)
			DetectedNPC = nil
		end
	end
end)

while wait() do
	for _, npc in pairs(NPCS:GetChildren()) do
		if (npc.HumanoidRootPart.Position - Player.Character.HumanoidRootPart.Position).magnitude < 15 then
			print("NPC Detected")
			if npc.Enabled.Value == true then
				npc.UpperTorso.EToGift.Enabled = true
				DetectedNPC = npc
				print(DetectedNPC)
			else
				npc.UpperTorso.EToGift.Enabled = false
				DetectedNPC = nil
			end
		else
			npc.UpperTorso.EToGift.Enabled = false
			DetectedNPC = nil
		end
	end
end

So i have this piece of code to loop through a folder with npc's in it. It checks if the player is in range and then checks if they pressed "E". But it only detects if you press e if you are next to the npc that is the last one in the folder. Any ideas?

1 answer

✓ Accepted answer

You are approaching this problem in a difficult way. It is always the last one because the script will first go through all the NPCs then once it hits wait will go and process the InputBegan. This gets into the green threads of Lua. Try something like this:

local Player = game.Players.LocalPlayer
local NPCS = game.Workspace:WaitForChild("NPCs")
local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(key)
    if key.KeyCode == Enum.KeyCode.E then
        print("Pressed E")
        if Player.Character and Player.Character:FindFirstChild("HumanoidRootPart") then
			for _, npc in pairs(NPCS:GetChildren()) do
				if (npc.HumanoidRootPart.Position - Player.Character.HumanoidRootPart.Position).magnitude < 15 then
					if npc.Enabled.Value then
						npc.UpperTorso.EToGift.Enabled = true
						game.Workspace.Events.DisableNPC:FireServer(npc)
					else
						npc.UpperTorso.EToGift.Enabled = false
					end
				else
            		npc.UpperTorso.EToGift.Enabled = false
				end
			end
		end
    end
end)

2 comments

0

It works but npc.UpperTorso.EToGift.Enabled = false is a billboardgui I want to activate when then player is close

0

Never mind I figured it out

This discussion is preserved as it was. New answers, comments, and votes are closed.