First of all: this is my first post on the forums, so woohoo!
Second of all, I have this issue where I’m making a custom healthbar for an NPC,
where there’s two frames (one is red, serving as the background, and the other is green, holding the main script) and the green one is supposed to change its size based on the health from the NPC.
Here’s the current script I have:
local npc = script.Parent.Parent.Parent.Parent -- Defines the npc's model
while true do
wait(0.01)
script.Parent.Size.X = UDim.new(npc.Humanoid.Health / 12, 0)
end
I’ve tried simply only changing the size to about halfway, trying other things, but nothing works.
so a couple of things here, but I’ll get straight to the point. I don’t think you can set the X and Y values individually through a script, as that will return an error (correct me if I’m wrong). you’d probably wanna do something like this; also, you have a second argument in Udim.new() which I think is wrong.
This is my first post as well! Sorry if there’s formatting issues with my reply.
There’s a few problems I noticed with your script.
You’re changing the size using script.Parent.Size.X which is read-only and also using UDim.new() which only has one dimension.
local npc = script.Parent.Parent.Parent.Parent
while true do
wait(0.01)
if npc:FindFirstChild("Humanoid") then
-- Calculate the new size
local hpPercentage = npc.Humanoid.Health / npc.Humanoid.MaxHealth
script.Parent.Size = UDim2.new(hpPercentage , 0, script.Parent.Size.Y.Scale, script.Parent.Size.Y.Offset)
end
end
Your script could use a little improvement besides that problem, too. Instead of constantly changing it in a while true do loop, you should instead check only when the health changes using :GetPropertyChangedSignal("Health"), which basically listens for a change of value, like in your case, Health.
local npc = script.Parent.Parent.Parent.Parent
if npc:FindFirstChild("Humanoid") then
npc.Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
local hpPercentage = npc.Humanoid.Health / npc.Humanoid.MaxHealth
script.Parent.Size = UDim2.new(hpPercentage , 0, script.Parent.Size.Y.Scale, script.Parent.Size.Y.Offset)
end)
end
Sorry if this code is not correct, I am using previous knowledge and I’m not able to test it right now since I’m super busy with other projects. Additionally, make sure all your variables are assigned to the correct thing!
Okay, so I tried the things you asked (aside from the .Changed thing) and my new code is like this:
local npc = script.Parent.Parent.Parent.Parent
while true do
task.wait(0.1)
script.Parent.Size = UDim2.new(npc.Humanoid.Health * 0.12, 0, 0, 0)
end
(I changed the health from being divided by 12 to being multiplied instead since i miscalculated)
and it is actually changing the size correctly, so hooray! However, it brought a new problem. The size is being changed correctly, but the green frame is just not displaying at all.