If you wanted it to show your health right on spawn, it might be a good idea to put something above the event which will fire essentially right when the script is loaded up. For example:
local Player = game.Players.LocalPlayer
local char = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = char:WaitForChild("Humanoid")
local healthtext = -- wherever healthtext is
local bar = -- wherever bar is
--whatever is here will run right on startup
healthtext.Text = Humanoid.Health.." / ".. Humanoid.MaxHealth
-- this is the event, whatever is in this codeblock will only happen whenever the health is changed
Humanoid.HealthChanged:Connect(function()
local CurrentHealth = char.Humanoid.Health
local MaxHealth = char.Humanoid.MaxHealth
healthtext.Text = CurrentHealth.." / "..MaxHealth -- quite possible that current health will end up as an ugly decimal here, like 11.3484729293 or whatever. you might want to round currentHealth
bar.Size = UDim2.new(CurrentHealth / MaxHealth, 0, 1, 0)
end)
Oh, I was under the assumption that this was simply a LocalScript in StarterCharacter or something. Well, one way you could go about this is wrapping this in a CharacterAdded, like so:
If youâre doing it on the server, yes. Otherwise, no. Because this is a serverScript, it will be unable to process changes on the client. If you were to go to âTestâ in a test session, then press on âCurrent: Clientâ , you can edit the change on the server. Once you go back onto the client, the changes will be shown there.
Add a variable to define the last amount of health your Humanoid has in the HealthChanged function so we can determine if the Humanoid has taken damage or not.
Do something like this:
local Humanoid = Player.Character.Humanoid
local LastHealth = Humanoid.Health
Humanoid.HealthChanged:Connect(function(h)
if h < LastHealth then
print("Player has taken damage!")
end
LastHealth = h -- Remember to update the LastHealth value so that if (for example) the player's health was to increase, and then to decrease from taking damage, it will correctly determine if the Player has taken damage.
end)