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 4 years ago
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

Log in to vote
0
Answered by 4 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:

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)

0
It works but npc.UpperTorso.EToGift.Enabled = false is a billboardgui I want to activate when then player is close Barty200 85 — 4y
0
Never mind I figured it out Barty200 85 — 4y
Ad

Answer this question