01 | local Player = game.Players.LocalPlayer |
02 | local NPCS = game.Workspace:WaitForChild( "NPCs" ) |
03 | local UIS = game:GetService( "UserInputService" ) |
04 | local DetectedNPC = nil |
05 |
06 | UIS.InputBegan:Connect( function (key) |
07 | if key.KeyCode = = Enum.KeyCode.E then |
08 | print ( "Pressed E" ) |
09 | if DetectedNPC then |
10 | print ( "Pressed E with npc nearby" ) |
11 | game.Workspace.Events.DisableNPC:FireServer(DetectedNPC) |
12 | DetectedNPC = nil |
13 | end |
14 | end |
15 | 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?
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:
01 | local Player = game.Players.LocalPlayer |
02 | local NPCS = game.Workspace:WaitForChild( "NPCs" ) |
03 | local UIS = game:GetService( "UserInputService" ) |
04 |
05 | UIS.InputBegan:Connect( function (key) |
06 | if key.KeyCode = = Enum.KeyCode.E then |
07 | print ( "Pressed E" ) |
08 | if Player.Character and Player.Character:FindFirstChild( "HumanoidRootPart" ) then |
09 | for _, npc in pairs (NPCS:GetChildren()) do |
10 | if (npc.HumanoidRootPart.Position - Player.Character.HumanoidRootPart.Position).magnitude < 15 then |
11 | if npc.Enabled.Value then |
12 | npc.UpperTorso.EToGift.Enabled = true |
13 | game.Workspace.Events.DisableNPC:FireServer(npc) |
14 | else |
15 | npc.UpperTorso.EToGift.Enabled = false |