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
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()
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.