Suggestions to improve code

Hey developers!

I wrote a HealthBarModule, it is able to change the size, color, and text of the bar. However, I am fairly new to OOP and I am unsure how to inprove this performance wise and just to make it cleaner. Any suggestions would be great.

LocalScript:

local RunService = game:GetService("RunService")
local HealthModule = require(script:WaitForChild("HealthModule"))

local Player = game.Players.LocalPlayer
local Character = script.Parent
repeat wait() until Character
local Humanoid = Character:FindFirstChild("Humanoid")

local Health = Player.PlayerGui:WaitForChild("HealthBar").Background.Health
local CurrentHealth = Player.PlayerGui:WaitForChild("HealthBar").Background.HealthAt

local Green = Color3.new(0.215686, 0.619608, 0.101961)
local Red = Color3.new(0.831373, 0, 0.0117647)

local HealthBar = HealthModule.New(Health)

Humanoid.HealthChanged:Connect(function()
	HealthBar:ChangeSize()
	HealthBar:ChangeText(CurrentHealth)
	HealthBar:ChangeColor(Red, Green)
end)

ModuleScript:

local Character = script.Parent.Parent

local HealthChanger = {}
HealthChanger.__index = HealthChanger

function HealthChanger.New(GuiHealth)
	local self = setmetatable({}, HealthChanger)
	
	self.HealthGui = GuiHealth
	
	return self
end

function HealthChanger:ChangeSize()
	self.HealthGui:TweenSize(UDim2.new(Character.Humanoid.Health / Character.Humanoid.MaxHealth, 0,0,100), "Out", "Linear", 0.25)
end

function HealthChanger:ChangeText(CurrentHealth)
	CurrentHealth.Text = math.floor(Character.Humanoid.Health) .. "/" .. Character.Humanoid.MaxHealth
end

function HealthChanger:ChangeColor(Red, Green)
	self.HealthGui.BackgroundColor3 = Red:Lerp(Green, Character.Humanoid.Health / Character.Humanoid.MaxHealth)
end

return HealthChanger
2 Likes

Every frame, you’re create a new object, which might cause memory leaks. Can’t you create it outside of the connection?

I feel like oop might not be very useful here, as most of the information is already stored in the humanoid instance.

1 Like

I feel like oop might not be very useful here, as most of the information is already stored in the humanoid instance.

Yeah, I just wanted to see how well I can do it using OOP. (I have a copy of it without OOP).

Every frame, you’re create a new object, which might cause memory leaks. Can’t you create it outside of the connection?

Yes, I can do that, thank you for telling me this information.

instead of using RunService, can’t you just make a healthbar at the start of the script then use the functions when the humanoid’s health changes?

instead of using RunService, can’t you just make a healthbar at the start of the script then use the functions when the humanoid’s health changes?

Good idea, I completely forgot about that event, thank you.