Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Help with NPC attack script only when attacked?

So lets pretend you have a NPC. If a player hits this NPC and lowers its health, then the NPC starts attacking and following that player. I have my script below which just follows the player and attacks them, but i need someone to add, adjust, or create a new script to do what i said in the fist sentence. It would be much appreciated.

So I need a NPC which attacks when his health is below 100 and stops when his health is back up to 100.

local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")

	function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent) then
			temp = temp2:findFirstChild("HumanoidRootPart")
			human = temp2:findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end


while true do
	wait(0.1)
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil then
		script.Parent.zombie:MoveTo(target.Position, target)
	end
end


4 comments

0

here is the model for anyone who wants to see it

0

If the NPC is attacked by a sword, see what the parent of the sword tool is, and make the NPC follow that player.

0

thedragonstriker25 to make we able to get the model, you need to make it purchasable

2 answers

I would put a stringvalue into the npc's humanoid and name it 'hitBy', if that value changes it looks loops through the players checking if any of them match the value's value.

Here's a better answer just do on line 3 script.Parent.zombie.HealthChanged:Wait()

This discussion is preserved as it was. New answers, comments, and votes are closed.