Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Detecting NPCS only detects the last npc in folder?

Asked by 5 years ago
01local Player = game.Players.LocalPlayer
02local NPCS = game.Workspace:WaitForChild("NPCs")
03local UIS = game:GetService("UserInputService")
04local DetectedNPC = nil
05 
06UIS.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
15end)
View all 34 lines...

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

Log in to vote
0
Answered by 5 years ago

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:

01local Player = game.Players.LocalPlayer
02local NPCS = game.Workspace:WaitForChild("NPCs")
03local UIS = game:GetService("UserInputService")
04 
05UIS.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
View all 23 lines...
0
It works but npc.UpperTorso.EToGift.Enabled = false is a billboardgui I want to activate when then player is close Barty200 85 — 5y
0
Never mind I figured it out Barty200 85 — 5y
Ad

Answer this question