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

How to make an NPC follow a player?

Here is what I have so far (Server Script inside the rig's model:

local NPC = script.Parent
local Humanoid = script.Parent:FindFirstChild("Humanoid")
local HRP = script.Parent:FindFirstChild("HumanoidRootPart")

local function GetClosestPlayer(range)
    local List = {}
	local Target = nil
	for i, v in pairs(game.Players:GetPlayers()) do
		local dist = v:DistanceFromCharacter(HRP.position)
		if dist <= range then
			table.insert(List, {dist, v})
		end
	end
		
	table.sort(List, function(A, B)
		return A[1] < B[1]
	end)
	
	pcall(function()
		Target = List[1][2]
	end)
	
	return Target
end

while true do
    wait(0.3)
    local Target = GetClosestPlayer(15) 
	if Target == nil then return end
	local char = Target.Character
	local hrp = char:WaitForChild("HumanoidRootPart")
    Humanoid:MoveTo(hrp.Position)
    Humanoid.MoveToFinished:Wait()
end

It errors:

Workspace.Dummy.Script:31: attempt to index nil with 'WaitForChild'

3 comments

0

Check whether Character is nil

0

You're attempting to index character with rbxscriptsignal. Make sure character is referenced.

0

It is.

1 answer

I think the reason is that you don't need to use the wait for child command if the script/object is already there. Try this: I might be wrong

local NPC = script.Parent
local Humanoid = script.Parent:FindFirstChild("Humanoid")
local HRP = script.Parent:FindFirstChild("HumanoidRootPart")

local function GetClosestPlayer(range)
    local List = {}
    local Target = nil
    for i, v in pairs(game.Players:GetPlayers()) do
        local dist = v:DistanceFromCharacter(HRP.position)
        if dist <= range then
            table.insert(List, {dist, v})
        end
    end

    table.sort(List, function(A, B)
        return A[1] < B[1]
    end)

    pcall(function()
        Target = List[1][2]
    end)

    return Target
end

while true do
    wait(0.3)
    local Target = GetClosestPlayer(15) 
    if Target == nil then return end
    local char = Target.Character
    local hrp = char.HumanoidRootPart
    Humanoid:MoveTo(hrp.Position)
    Humanoid.MoveToFinished:Wait()
end

4 comments

0

I was going to say the same thing; there is nothing to wait for when you have it already there

0

Didn't work. It says attempt to index nil with HumanoidRootPart. :/

1

This may happen because the Character don't exist, try: local char = Target.Character or Target.CharacterAdded:Wait() I guess?

0

Didnt work

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