So I’m having an issue. I’m trying to make it so when someone is attacking an NPC it checks if they are below level 10, and if they are not, it will fire a client event. No errors are being produced.
Here is the script:
local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local AttackBlockedEvent = ReplicatedStorage:WaitForChild("Events"):WaitForChild("AttackBlocked")
local function onHealthChanged(oldHealth, newHealth)
if newHealth < oldHealth then
local attacker = humanoid:FindFirstChild("creator")
if attacker and attacker:IsA("ObjectValue") and attacker.Value and attacker.Value:IsA("Player") then
local player = attacker.Value
local stats = player:FindFirstChild("Stats")
if stats then
local level = stats:FindFirstChild("Level")
if level and level.Value < 10 then
humanoid.Health = oldHealth
AttackBlockedEvent:FireClient(player)
end
end
end
end
end
humanoid.HealthChanged:Connect(function(newHealth)
onHealthChanged(humanoid.Health, newHealth)
end)
It is a server script by the way, inside of the npc. (the npc is in the workspace) I went through all that earlier.
Your issue is here.
As you can see in the docs of humanoid.HealthChanged it gives you the new health of the humanoid and you check if Humanoid.Health is less than newhealth. This will always return false because both values will always be the same. To solve this you can compare it with the health the npc had before it got damaged
local function onHealthChanged(oldHealth, newHealth)
if newHealth < oldHealth then
-- this can never run
end
end
humanoid.HealthChanged:Connect(function(newHealth)
onHealthChanged(humanoid.Health, newHealth)
end)
local oldHealth = humanoid.Health
humanoid.HealthChanged:Connect(function(newHealth)
if newHealth < oldHealth then
print("Damaged!")
end
oldHealth = newHealth
end)
The issue in your code was that it could never reach a certain point.
local function onHealthChanged(oldHealth, newHealth)
if newHealth < oldHealth then -- This would always be false
-- code here can never run
local attacker = humanoid:FindFirstChild("creator")
if attacker and attacker:IsA("ObjectValue") and attacker.Value and attacker.Value:IsA("Player") then
local player = attacker.Value
local stats = player:FindFirstChild("Stats")
if stats then
local level = stats:FindFirstChild("Level")
if level and level.Value < 10 then
humanoid.Health = oldHealth
AttackBlockedEvent:FireClient(player)
end
end
end
end
end
And i pointed out what you should do to change it so that the rest of your function is able to execute.