Can someone tell me how to optimize my code?

Hi I was wondering if this script could be improved for performance (cause someone told me it was not well optimized)

while wait() do
	local player = game.Players.LocalPlayer
	local playername = player.Name
	local TycoonModel = workspace.Tycoons
	local Values = TycoonModel.Tycoon:FindFirstChild("Values")
	for i, x in pairs(TycoonModel:GetChildren()) do
		if player:FindFirstChild("OwnsTycoon").Value == true then
			if x.Values.OwnerValues.Value.Name == playername then
				script.Parent.Text = Values.OilValue.Value
			end
		end
	end
end
1 Like

so this supposed to run everything

you can use Changed() and move out this statement in the loop

and also remove the infinity loop that would check the statement everytime

Changed() will check it everytime :ok_hand:

local Player = game.Players.LocalPlayer
local PlayerName = Player.Name
local TycoonModel = workspace.Tycoons

local Values = TycoonModel.Tycoon:FindFirstChild("Values")
local OwnsTycoon = Player:FindFirstChild("OwnsTycoon")

if OwnsTycoon then
	OwnsTycoon.Changed:Connect(function(Value)
		if Value then 
			for i, x in pairs(TycoonModel:GetChildren()) do
				if x.Values.OwnerValues.Value.Name == PlayerName then
					script.Parent.Text = Values.OilValue.Value
				end
			end
		end
	end)
end
3 Likes