So I am trying to make a HealthBar according to the player's Health. And I made this script, but its not working for some reason. Any help? --HealthBar script
01 | local Player = game.Players.LocalPlayer |
02 | local PlayerHealth = Player.Character:WaitForChild( "Humanoid" ).Health |
03 | game.Players.PlayerAdded:Connect( function () |
04 | while true do |
05 | wait() |
06 |
07 | local Health = PlayerHealth |
08 | local MaxHealth = Player.leaderstats.MaxHealth |
09 |
10 | local math = ( Health / MaxHealth ) |
11 |
12 | script.Parent:TweenSize(UDim 2. new(math, 0 , 1 , 0 ), "Out" , "Quad" ,. 25 ) |
13 | end |
14 | end ) |
--MaxHealth script
1 | game.Players.PlayerAdded:Connect( function (player) |
2 | local leaderstats = Instance.new( "IntValue" , player) |
3 | leaderstats.Name = "leaderstats" |
4 | leaderstats.Parent = player |
5 |
6 | local MaxHealth = Instance.new( "IntValue" , leaderstats) |
7 | MaxHealth.Name = "Max Health" |
8 | MaxHealth.Value = 100 |
9 | end ) |
Assuming MaxHealth inside the leaderstats is a value instance, it should be local MaxHealth = Player.leaderstats.MaxHealth.Value
(on line 8)
So first, I don't think you really need to be tracking the MaxHealth of a player with an IntValue. The player's character's humanoid already has a value for that.
What you would want to do is have your...
1 | game.Players.PlayerAdded:Connect( function (player) |
2 | ... |
3 | end ) |
But also character added event inside...
1 | player.CharacterAdded:Connect( function (character) |
2 | ... |
3 | end ) |
From there you would get the humanoid...
1 | local humanoid = character.Humanoid |
And then have a humanoid health changed event...
1 | humanoid.HealthChanged:Connect( function (health) |
2 |
3 | end ) |
Inside that you would do your calculations...
1 | humanoid.HealthChanged:Connect( function (health) |
2 | local percentage = health / humanoid.maxHealth |
3 | -- From here you can't change the player's guis from the server side so you will have to fire a RemoteEvent to the client and change the UI stuff there |
4 | end ) |
1 | -- Client Local Script |
2 |
3 | RemoteEvent.OnClientEvent:Connect( function (percentage) |
4 | HealthBar:TweenSize(UDim 2. new(percentage, 0 , 1 , 0 ), "Out" , "Quad" ,. 25 ) |
5 | end ) |
That's how you would do it directly from the server side, but you could also do it entirely from a Local Script since whatever happens to the player's health on the server will replicate to the client. Where you would eliminate the playeradded, and do everything I just said on the client side.