Hello! I am making an attack script that attacks the player whenever the player attacks the NPC. I made the script and all but when I test it out and attack the guard, it doesn’t even move. All it says is, “No attacker found”. I made it print stuff to help me find out what’s the problem. Here is the code.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local PathFindingService = game:GetService("PathfindingService")
local players = game:GetService("Players")
local sword = script.Parent:WaitForChild("ClassicSword")
local be = script.Parent:WaitForChild("ToolBe")
-- Variables
local char = script.Parent
local hrp = char:WaitForChild("HumanoidRootPart")
local hum = char:WaitForChild("Humanoid")
local guardTemplate = ReplicatedStorage:WaitForChild("Guard") -- well... this is pretty self-explanatory
guardTemplate.HumanoidRootPart.CFrame = CFrame.new(-45, 13.141, -66)
char.Humanoid:UnequipTools()
local lastAttacker = Instance.new("ObjectValue")
lastAttacker.Name = "LastAttacker"
lastAttacker.Parent = hum
local function SwingSword(npc, player)
local character = player.Character
if character then
be:Fire()
end
end
local function Move(npc, attackerCharacter)
local npcHumanoid = npc:FindFirstChild("Humanoid")
local npcRoot = npc:FindFirstChild("HumanoidRootPart")
local attackerRoot = attackerCharacter:FindFirstChild("HumanoidRootPart")
if npcHumanoid and npcRoot and attackerRoot then
while attackerCharacter and attackerCharacter:FindFirstChild("Humanoid") and attackerCharacter.Humanoid.Health > 0 do
local path = PathFindingService:CreatePath({
AgentRadius = 2,
AgentHeight = 5,
AgentCanJump = true,
AgentJumpHeight = 7,
AgentMaxSlope = 45
})
path:ComputeAsync(npcRoot.Position, attackerRoot.Position)
if path.Status == Enum.PathStatus.Complete then
local waypoints = path:GetWaypoints()
for _, waypoint in ipairs(waypoints) do
npcHumanoid:MoveTo(waypoint.Position)
local reached = npcHumanoid.MoveToFinished:Wait()
if reached and (npcRoot.Position - attackerRoot.Position).Magnitude <= 3 then
SwingSword(npc, players:GetPlayerFromCharacter(attackerCharacter))
wait(1)
break
end
end
else
warn("Pathfinding failed for " .. npc.Name)
break
end
wait(0.5)
end
end
end
local function onDamaged(attacker)
if attacker then
local attackerPlayer = players:GetPlayerFromCharacter(attacker)
if attackerPlayer then
print(attackerPlayer.Name .. " attacked the NPC.")
char.Humanoid:EquipTool(sword)
Move(char, attacker)
end
end
end
hum.HealthChanged:Connect(function()
if hum.Health < hum.MaxHealth then
if lastAttacker.Value then
print("Health dropped! Attacker:", lastAttacker.Value.Name)
onDamaged(lastAttacker.Value)
else
print("No attacker detected.")
end
end
end)