Hello, i don't know what is the problem in my script but help me! thanks.
local mob = script.Parent.Parent.Parent.Parent.player.Humanoid.Health local mobmax = script.Parent.Parent.Parent.Parent.player.Humanoid.MaxHealth while true do wait(0.01) script.Parent.HealthNum.Text = math.floor(mob) .. " / " .. math.floor(mobmax) local pie = (mob / mobmax) script.Parent.Healthbar.Size = UDim2.new(pie, 0, 1, 0) end
WaitForChild
WaitForChild
method in this code is just asking for an error. You cannot confirm that any object you're trying to access within the script will be loaded and ready to use at run time, therefore WaitForChild (or at very least, FindFirstChild
) should be implimented.Loops
event
specifically for when the Humanoid's health is changed called "HealthChanged", deprecating the need to constantly check the health over and over.Local script
LocalPlayer
LocalPlayer
feature which is a member of the Players
service (exclusively for local scripts). This will return the player the script is a descendant of, instead of needing to write out it's full hierarchy.Character
wait
method of the CharacterAdded
event, combined with an or condition
that chooses it's alternative if the character does not exist. Here's an example:-- Gets, or waits and returns the character. local char = player.Character or player.CharacterAdded:wait()
So applying all I went over above, we should have something like this:
-- Getting the local player local player = game:GetService("Players").LocalPlayer -- Gets, or waits and returns the character. local char = player.Character or player.CharacterAdded:wait() -- Using WaitForChild to load the Humanoid. local human = char:WaitForChild("Humanoid") -- Get the health bar local healthBar = script.Parent:WaitForChild("Healthbar") -- Get the text label local healthNum = script.Parent:WaitForChild("HealthNum") -- Now connecting the event called "HealthChanged" which fires obviously, when the humanoid's health is changed. human.HealthChanged:connect(function(health) local max = human.MaxHealth -- Update the info with the given stats healthNum.Text = math.floor(health).."/"..max healthBar.Size = UDim2.new(health/max,0,1,0) end) -- End the event.
Hope that helped, if you have any questions let me know.