Custom NPC healthbar

I’m rather new to scripting on Roblox, so I’m expecting to make a fool of myself.

I’m trying to set up a healthbar for an enemy NPC and it works great, but only when I run the game.
Upon testing the game and damaging the Humanoid, the healthbar will not change.
Upon running the game and damaging the Humanoid, the healthbar will change.

Script:

local char = script.Parent.Parent.Parent.Parent.Parent:WaitForChild("Humanoid")
function roundnumber(n)											
	 return math.floor(n+0.5)
end
char.HealthChanged:Connect(function(HP)							
	print("working")											
	script.Parent.Size = UDim2.new(char.Health/char.MaxHealth,0,1,0) 
	script.Parent.TextLabel.Text = roundnumber(char.Health)		
	if char.Health == 0 then									
		script.Parent.Parent.Parent.Enabled = false
	end
end)

Char is the NPC’s humanoid.
The roundnumber function does what it says, it rounds the health to avoid large decimal places.
‘working’ is printed when running, but not playing.
The scripts parent is a frame representing health.
The ‘if’ statement removes the healthbar once the NPC is dead.
Sorry if this was all obvious, just figured better safe than sorry.

I haven’t been able to figure out why it only works when running and I’m sure it’s something simple, and I’ve tried to do this in multiple ways and it has the same result every time.

Thanks a bunch : )

3 Likes

When “running”, do you test if the health bar is working by setting the health of the NPC manually?

It’s possible that you’re not dealing damage to the NPC properly. I think it would be also good to know how you’re dealing damage to the NPC when you’re playing.

Perhaps the “tool” you’re using to damage the humanoid while testing, it might have been a tool that does not support FE(it’s only a LocalScript) and the damage sent is “0” in server.

Oh, and I just figured out that you were changing the health from “CLIENT” and not “SERVER”. While testing, you can find a button that switches between client and server perspective. Understanding replication would be the ideal solution.

1 Like

When “running”, do you test if the health bar is working by setting the health of the NPC manually?

I set the health manually whilst both running and playing.

By default, when you play the game in studio, everything you do is done in a “client” context. This means that changes you do (via the properties window, explorer, etc.) won’t be replicated to the server.

To switch from client to server, click this button:

image

Thank you so much!
I just put a sword in the starterpack and attacked the npc, and it works perfectly.
Turns out I was just being a fool :sweat_smile: