Hey guys im trying to get a npc to chase me i have this in serverscriptstorage and it's respawn and chasing mechanic work fine but I only want it to happen if a part is touched then it starts chasing me ive tried a few things but they dont work here's my script
local npc = game.Workspace.NPC
local humanoid = npc:WaitForChild("Humanoid")
local rootPart = npc:WaitForChild("HumanoidRootPart")
local Players = game:GetService("Players")
local respawnTime = 3
local npcSpawnPoint = rootPart.Position
local npcParent = npc.Parent
local npcClone = npc:Clone()
local walkSpeed = 50
local function getNearestPlayer()
local nearestPlayer = nil
local shortestDistance = math.huge
for _, player in pairs(Players:GetPlayers()) do
local character = player.Character
if character and character:FindFirstChild("HumanoidRootPart") then
local distance = (rootPart.Position - character.HumanoidRootPart.Position).magnitude
if distance < shortestDistance then
shortestDistance = distance
nearestPlayer = character
end
end
end
return nearestPlayer
end
local function followNearestPlayer()
while humanoid.Health > 0 do
local target = getNearestPlayer()
if target then
humanoid:MoveTo(target.HumanoidRootPart.Position)
humanoid.WalkSpeed = walkSpeed
humanoid.MoveToFinished:Wait()
end
wait(0.01)
end
end
local function respawnNPC()
wait(respawnTime)
local newNPC = npcClone:Clone()
newNPC.Parent = npcParent
newNPC:SetPrimaryPartCFrame(CFrame.new(npcSpawnPoint))
script.Parent = newNPC
newNPC:FindFirstChild("Humanoid").Died:Connect(respawnNPC)
followNearestPlayer()
end
humanoid.Died:Connect(respawnNPC)
followNearestPlayer()