Hi! So i was making a healthbar for my game and it works fine in studio, but in game it doesnt work and gives me the error that “Humanoid is not apart of character” or something like that. This causes the healthbar to show 100 hp when they arent. Here is my code for the bar:
local player = game.Players.LocalPlayer
local character = player.Character
local humanoid = character.Humanoid
repeat task.wait() until player
repeat task.wait() until character
repeat task.wait() until humanoid
humanoid.HealthChanged:Connect(function(damage)
script.Parent.Size = UDim2.new(damage / humanoid.MaxHealth, 0, 1, 0)
end)
here is my code for the text of the healthbar:
local player = game.Players.LocalPlayer
local character = player.Character
local humanoid = character.Humanoid
local healthlabel = script.Parent
repeat task.wait() until player
repeat task.wait() until character
repeat task.wait() until humanoid
repeat task.wait() until healthlabel
humanoid.HealthChanged:Connect(function()
local health = humanoid.Health
healthlabel.Text = health
end)
repeat task.wait() until x doesn’t work in this case, you would want to use: local humanoid = character:WaitForChild("Humanoid")
in the case of looking for a child object (like the humanoid under the character)
and local character = player.Character or player.CharacterAdded:Wait()
when looking for the players character.
the reason you have to do this is the script sometimes runs before all the game objects load in, :WaitForChild() causes the code to stall until that object exists. and .CharacterAdded is a event that fires when the player loads their character in, by doing a :Wait() on it you make the code stall until the event fires.
There is no need to do it for script.Parent as the script cannot run until its own parent is loaded.
alright thanks. i was confused because i knew this was the issue but i didnt know how to fix it. ill mark this as solution and ill fix it soon. thank you!