Search code examples
luarobloxluau

HealthBar in Roblox Studio


Im develop game in Roblox Studio, but my HealthBar not working. My code:

local text = game.StarterGui.HealthBar.Health.Bar
print("Script started")
---------------------------------------------------------
game.Players.PlayerAdded:Connect(function(player)
    print("Player add")
    player.CharacterAdded:Connect(function(character)
        print("Character add")
        local healthText = character.Humanoid.Health
        local function updateHealth(healthText)
            text.Text = healthText
        end
        character.Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
            updateHealth(healthText)
        end)
    end)
end)
---------------------------------------------------------
print("Script ended")

It was supposed to show the health level in numbers, but it doesn't show anything. P.S: im speak English so-so.


Solution

  • There is a few things wrong with your script:

    • its looks to be a server sided script, GUI should be edited in a client sided script. read more about this here
    • you're editing the StarterGui instead of PlayerGui. the client just simply clones the version inside the StarterGui to the PlayerGui
    • i would also be better to use WaitForChild on the humanoid.
    • you updated it to a fixed version of character.Humanoid.Health

    What i recommend doing is create a LocalScript inside the game.StarterGui.HealthBar.Health.Bar. inside this script i would put the following code:

    -- // Services \\ --
    local Players = game:GetService("Players");
    
    -- // Variables \\ --
    local Bar = script.Parent;
    local client = Players.LocalPlayer;
    
    -- // Events \\ --
    client.CharacterAdded:Connect(function(Character)
       local Humanoid = Character:WaitForChild("Humanoid");
    
       Humanoid.HealthChanged:Connect(function(Health)
          Bar.Text = Health;
       end);
    end);