Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How would I make this script shorter with a generic for loop?

HUD.Health.Tray.Beat.Line1.BackgroundColor3 = (
				(Humanoid.Health > 200 / 3) and Color3.fromRGB(0,255,0) or
				(Humanoid.Health <= 200 / 3 and Humanoid.Health > 100 / 3) and Color3.fromRGB(255,255,0) or
				(Humanoid.Health <= 100 / 3) and Color3.fromRGB(170,0,0)
		
			)

I want all the children of Beat to do this, I've already tried

for i,v in pairs(script.HealthGui.HUD.Health.Tray.Beat:GetChildren()) do
    if v:IsA("Frame") then
			v.BackgroundColor3 = (
				(Humanoid.Health > 200 / 3) and Color3.fromRGB(0,255,0) or
				(Humanoid.Health <= 200 / 3 and Humanoid.Health > 100 / 3) and Color3.fromRGB(255,255,0) or
				(Humanoid.Health <= 100 / 3) and Color3.fromRGB(170,0,0)
		
			)

4 comments

0

Do you need to calculate this each time or can you just use the same value for all of the frames?

0

Same value

0

Then just do the logic once then pass the same Color3 object to all of the frames in the loop

0

Answer edited.

1 answer

This is an example only using the code above:-

function findColor(hp)
	-- you could also work out the math e.g. 200/3 as this will be calculated each timw
	return (hp > 200 / 3) and Color3.fromRGB(0,255,0) or (hp <= 200 / 3) and (hp > 100 / 3) and Color3.fromRGB(255,255,0) or (hp <= 100 / 3) and Color3.fromRGB(170,0,0)
end

local newColor = findColor(Humanoid.Health )

for i,v in pairs(script.HealthGui.HUD.Health.Tray.Beat:GetChildren()) do
		if v:IsA("Frame") then  v.BackgroundColor3  = newColor   end
end

-- you could also make a list of all frames instead of checking for it in the loop
local frmList = {}
for i,v in pairs(script.HealthGui.HUD.Health.Tray.Beat:GetChildren()) do
		if v:IsA("Frame") then  table.insert(frmList, v)   end
end

-- then just use the frame list now we don't need to check if its a frame each time
for i,v in pairs(frmList) do
	 v.BackgroundColor3  = newColor 
end

Hope this helps, pls commet if you do not understand how/why this code works.

6 comments

0

there's an error on line 4

0

missed one ")" XD

0

I tried end) but it still gives an error

0

rip it broke the script

0

what's wrong with the second script I gave you

0

As i said i have updated my answer with the missing ")" you do not need to add one in.

This discussion is preserved as it was. New answers, comments, and votes are closed.