Is there anyway to optimize my script?

Hi, so i wanted to ask is there anyway to optimize my code its around 68 lines and i dont like lengthy scripts so i want to optimize it, but i dont know how to start

Heres the script i use it in every buyable button:

local A = false

local Parent = script.Parent

local Item = game.ReplicatedStorage.Buyables.FlourBag

local Item2 = game.ReplicatedStorage.Buyables.Conveyor

local Button = game.ReplicatedStorage.Buyables.YeastButton

local Button2 = game.ReplicatedStorage.Buyables.WaterButton

local DropScript = Item.DropScript

local Fold = game.Workspace:WaitForChild("tycoon1")

local DropType = Fold.DropType

local FlourTransport = Item.Flour

local Price = 0

local Text = Parent["Price&Item"]["Price&ItemText"]

Text.Text = Item.Name.. ": " ..Price

local function Showbuttons()
	Button.Parent = Fold
	Button2.Parent = Fold
end

Parent.Touched:Connect(function(hit)
if A == false then
		A = true
	if hit.Parent:FindFirstChild("Humanoid") then
		local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
		if plr then
			
			local cash = plr:WaitForChild("leaderstats").Coins
	
	if cash.Value >= Price then
			cash.Value -= Price

					print("bought!")
					
					Item.Parent = Fold
					
					Item2.Parent = Fold
					
					DropScript.Parent = Fold
					
					FlourTransport.Parent = Fold.Mixer
					
					DropType.Value = "FlourBall"
					
					Showbuttons()
					
					Parent.Parent:Destroy()
					
		elseif cash.Value < Price then
		print("To broke!")
		wait(2)
		A = false
				end
			end
		end
	end
end)

Dont have blank lines in between variables.

1 Like

that doesn’t help in optimization, infact it just makes your code look compact and maybe cleaner, depending on how you see it.

make game.ReplicatedStorage or game.ReplicatedStorage.Buyables a variable and use that instead of repetitively defining it like this. also use game:GetService("ReplicatedStorage") as it is better practice instead of directly defining them

this and any other wait() functions you have in your script should be task.wait. the task library is faster and more efficient

game.Players should be game:GetService("Players") in a separate variable

also, is this in a localscript? you should not be handling cash and price functions as it wont actually make a difference in the server (your actual cash value).

if this is a serverscript, *please don’t handle ui in the server. it can introduce performance issues.

Mixed up on what OP needed, however still removing the empty lines would probably still make it readable.

Optimization wise, make variables for services instead of using them like: game.ReplicatedStorage....