Can anyone help me, please? I had struggled to figure out why the NPCs weren’t moving. I don’t know what to do.
Here’s code NPCBehavior:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local AnimationFolder = ReplicatedStorage:WaitForChild("NPCAnimation")
local walkAnim = AnimationFolder:WaitForChild("WalkAnimation")
-- Bindable event for NPC behavior
local NPCBehaviorBindableEvent = ReplicatedStorage:WaitForChild("NPCRemote"):WaitForChild("NPCBehaviorEvent")
-- Function to make the NPC walk along its specific path
local function makeNPCWalk(npc, pathFolder)
-- Ensure the NPC has a humanoid
local humanoid = npc:FindFirstChildOfClass("Humanoid")
if not humanoid then
warn("NPC does not have a Humanoid! NPC Name: " .. npc.Name)
return
end
print("NPC has humanoid!")
-- Ensure the NPC has a PrimaryPart set (needed for MoveTo)
if not npc.PrimaryPart then
warn("NPC does not have a PrimaryPart set! NPC Name: " .. npc.Name)
return
end
-- Load and play the walk animation
local animTrack = humanoid:LoadAnimation(walkAnim)
animTrack:Play()
print("Walk animation started!")
-- Get all waypoints in the path folder
local waypoints = {}
for _, part in pairs(pathFolder:GetChildren()) do
if part:IsA("Part") then
table.insert(waypoints, part)
end
end
if #waypoints == 0 then
warn("No waypoints found for NPC: " .. npc.Name)
return
end
print("Waypoints found: " .. #waypoints)
-- Sort waypoints by position (optional if you want a set order)
table.sort(waypoints, function(a, b)
return a.Position.X < b.Position.X
end)
-- Make the NPC follow the waypoints
for _, waypoint in pairs(waypoints) do
if humanoid and npc then
print("Moving NPC to waypoint: " .. waypoint.Name) -- Debugging print
humanoid:MoveTo(waypoint.Position)
-- Wait until the NPC reaches the waypoint
humanoid.MoveToFinished:Wait()
print("NPC reached waypoint: " .. waypoint.Name) -- Debugging print
end
end
-- Stop the walk animation when done
animTrack:Stop()
print("NPC finished walking.") -- Debugging print
end
-- Listen for the BindableEvent to trigger NPC walking
NPCBehaviorBindableEvent.Event:Connect(function(npc, pathFolder)
-- Ensure both npc and pathFolder are valid
if npc and pathFolder then
print("Triggering NPC walk: " .. npc.Name) -- Debugging print
makeNPCWalk(npc, pathFolder)
else
warn("NPC or PathFolder is nil!")
end
end)