Chase-Script not working

Hello! So I’m trying to make a Chase-Script but for some reason it’s not working.
Script:

local nearestTarget = nil
local distance = 100
local players = game:GetService("Players")
local npc = workspace.NPC

local function chaseTarget(target)
	print("chasetarget")
	--The target is the humanoidRootPart
	local NPCHumanoid = npc.Humanoid
	print(target.Name .. " is the target")
	NPCHumanoid:MoveTo(target.Position)
end

local function findNearestTarget()
	
	for i,v in next, game.Players:GetChildren() do
		local char = workspace:FindFirstChild(v.Name) or workspace:WaitForChild(v.Name)
		local humanoidRootPart = char.HumanoidRootPart
		print((npc.HumanoidRootPart.Position - humanoidRootPart.Position).magnitude)
		if (npc.HumanoidRootPart.Position - humanoidRootPart.Position).magnitude < distance then
			print("magnitude was smaller")
			--Chase him 
			nearestTarget = humanoidRootPart
			return nearestTarget
		end
	end
end


while true do
	wait(0.5)
	local found = findNearestTarget()
	if found then
		print("found")
		chaseTarget(found)
	end
end

Everything prints.
Explorer:


Output:
image
That means everything should work.
Thank you!

Maybe it’s because of the NPC?

I inserted it through Build Rig. It’s a Mesh Rig (R15).

BuildRig anchors the HumanoidRootPart. Unanchor for movement.

1 Like

My script works perfectly now. Thank you!

1 Like

Btw. why didn’t you use player.Character for character? It’s the best method for this.

Also you should improve this with pathfinding.

1 Like

I got bad experience with player.Character so I usually do workspace:FindFirstChild(player.Name) or workspace:WaitForChild(player.Name).
Sometimes my script just infinite yielded when I did player:WaitForChild(“Character”) or player:FindFirstChild(“Character”)

The best practice is to reference through the player.
Finding through the workspace can cause issues - if a player is named Folder and you have a folder named this, you could get the wrong instance.

Player.Character should work in your case. In cases where you want the local character before executing, try local Character = Player.Character or Player.CharacterAdded:Wait()

1 Like

Wouldn’t you do
Player:FindFirstChild(“Character”) or Player.CharacterAdded:Wait() so it doesn’t error when there is no Character yet?

The or operator is there for the rare cases when the first Player.Character returns nil.
Player.CharacterAdded:Wait() will yield until the CharacterAdded event is fired.

Wouldn’t Player.Character error and not return nil?
That’s like doing

local var = workspace.thisisnotinmyworkspace

This would error too.

1 Like

No. It would not error if one option from the or / and operators are nil.

1 Like