Blocking/Health function still taking damage

I am trying to create a “blocking” script that makes you take no damage when holding F. I have the animation part done, and all of the variables, but I cannot seem to figure out the damage. Nothing (besides the prints) are shown in the output, so I do not know what the problem is.

Here is the part of the script that handles damage:

local plr = game.Players.LocalPlayer
local char = plr.Character 
 
local hum = game.Players.LocalPlayer.Character:WaitForChild("Humanoid") 

local hp = hum.Health

local function onHealthChanged(health)
	print("took damage")
	hp = health
	if isBlocking then
		hum.Health = health
		print(health)
	end
end

if hum then
	hum.HealthChanged:Connect(onHealthChanged)
end

char.Humanoid.HealthChanged:Connect(onHealthChanged)

Here is my full script:

local UserInputService = game:GetService("UserInputService")
local rs = game:GetService("ReplicatedStorage")

local plr = game.Players.LocalPlayer
local char = plr.Character

local events = rs:WaitForChild("Events")
local contblock = events:WaitForChild("Block")

local hum = game.Players.LocalPlayer.Character:WaitForChild("Humanoid")
local animator = hum:WaitForChild("Animator")

local hp = hum.Health

local contblockAnim = animator:LoadAnimation(script:WaitForChild("ContBlock"))

local isBlocking = false

local function playAnimation()
	if not isBlocking then
		isBlocking = true
		contblockAnim:Play()
	end
end

local function stopAnimation()
	if isBlocking then
		isBlocking = false
		contblockAnim:Stop()
	end
end

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.F then
		playAnimation()
	end
end)

UserInputService.InputEnded:Connect(function(input, gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.F then
		stopAnimation()
	end
end)

local function onHealthChanged(health)
	print("took damage")
	hp = health
	if isBlocking then
		hum.Health = health
		print(health)
	end
end

if hum then
	hum.HealthChanged:Connect(onHealthChanged)
end

char.Humanoid.HealthChanged:Connect(onHealthChanged)
local blockEvent = rs.Events:FindFirstChild("Block")

Please help if you can, thank you!

In the OnHealthChanged Event, the health variable points to the humanoid’s new hp.

So you are saving the new health to hp and changing the hp to be the same as it would already be. instead try this

local function onHealthChanged(health)
print(“took damage”)
if isBlocking then
hum.Health = hp
end
hp = hum.Health
end

This should update the hp value no matter what, and restore it if you are blocking.

1 Like

Thank you so much!!! I’ve been working on this for a few days now, just fixing this one part lol :pray:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.