Attack Script not working properly

Hey Developers!
I am currently making a story game, and I am at the part where the NPC attack comes, my NPC is a thief, it works, but not as it should, all it does is teleports to their HumanoidRootPart, it doesn’t walk at all, also, how could I improve it so that it works smoothly for an R6 character?

Script:

local Thief = script.Parent

function AttackPlayer()
	local Players = game.Players:GetChildren()
	local ChosenPlayer = Players[math.random(1,#Players)]
	if ChosenPlayer.Character:FindFirstChild('HumanoidRootPart') then
		Thief.HumanoidRootPart.CFrame = ChosenPlayer.Character.HumanoidRootPart.CFrame
		Thief.Humanoid:MoveTo(ChosenPlayer.Character.HumanoidRootPart.Position)
		Thief.Humanoid.MoveToFinished:Wait()
		ChosenPlayer.Character.Humanoid.Health = ChosenPlayer.Character.Humanoid.Health - 4
		wait(1)
	end
end

while true do
	wait(2)
	AttackPlayer()
end

Thanks for any help!

You could make a part and use the :Touched() event, as a detector.

This script is suppposed to automatically supposed to find players and attack them…

Hey, it’s because before using :MoveTo() you are teleporting the NPC to the player.

Thief.HumanoidRootPart.CFrame = ChosenPlayer.Character.HumanoidRootPart.CFrame

Deleting this line should fix your problem.

Is there anyway to improve the script though? or is this decent?

After deleting the line, it should work, though if you’re looking for suggestions, I’d suggest instead of looking for a random player online, you could see which is the closest and whether he/she is within a certain distance. I imagine you wouldn’t want the NPC trying to run in a straight line to a player halfway across the map :stuck_out_tongue:
Also, if a player doesn’t have a character loaded in, then its Character should be nil, which would result in an error when you try to call FindFirstChild() on it. Instead of looking for a HumanoidRootPart, maybe you should see if the player has a character.

1 Like

@gamingguy88 mentioned improvement, also make sure to mark something as solution.