How can I make this animated flag script to be less performance heavy?

So I found an animated flag in free models where it creates an “animated” flag by toggling transparency on frame-by-frame flag mesh parts, but I found the code to be very messy and a bit laggy, so I rewrote the code a bit to use loops instead of manually toggling transparency for all 16 frames.

Original code:

sp=script.Parent
flag=sp.Flag

reset=function()
	for _,meshpart in pairs (flag:GetChildren()) do
		if meshpart:IsA("MeshPart") then
			meshpart.Transparency=1
		end
	end
end

waittime=.01 --Time between each "Frame"

while true do
	wait(waittime)
	reset()
	flag["2"].Transparency=0
	wait(waittime)
	reset()
	flag["3"].Transparency=0
	wait(waittime)
	reset()
	flag["4"].Transparency=0	
	wait(waittime)
	reset()
	flag["5"].Transparency=0
	wait(waittime)
	reset()
	flag["6"].Transparency=0
	wait(waittime)
	reset()
	flag["7"].Transparency=0
	wait(waittime)
	reset()
	flag["8"].Transparency=0
	wait(waittime)
	reset()
	flag["9"].Transparency=0
	wait(waittime)
	reset()
	flag["10"].Transparency=0
	wait(waittime)
	reset()
	flag["11"].Transparency=0
	wait(waittime)
	reset()
	flag["12"].Transparency=0
	wait(waittime)
	reset()
	flag["13"].Transparency=0
	wait(waittime)
	reset()
	flag["14"].Transparency=0
	wait(waittime)
	reset()
	flag["15"].Transparency=0
	wait(waittime)
	reset()
	flag["16"].Transparency=0
	wait(waittime)
	reset()
	flag["1"].Transparency=0
end

My code:

local sp = script.Parent
local flag = sp.Flag

local running = false
local waitTime = 0.05

while true do
	wait(waitTime)
	if not running then
		running = true
		for i = 1, 16 do
			if i == 1 then -- default to making frame #1 invisible 
				flag[tostring(16)].Transparency = 1
			else
				flag[tostring(i-1)].Transparency = 1
			end
			
			flag[tostring(i)].Transparency = 0
			wait(waitTime)
		end
		running = false 
	end
end

Images:

image
image

Problem:

However, both versions of the code are only lightweight on performance whenever only one flag is active. When there’s only one animated flag, the script activity only slightly fluctuates and the script rate stays at about 4-5 per second. (recorded after 60 seconds)

image

When there is more than one animated flag, the script activity fluctuates a bit more, and the script rate shoots up very quickly. (recorded after 60 seconds)

image

I also tried changing the while loop with a Heartbeat anonymous function but it had much worse performance (probably since it was running a lot more frequently)

image

That being said, is there a way to optimize the code so that its script rate wouldn’t shoot up like that, and so that I can have multiple animated flags without it being laggy?

AnimatedFlags.rbxm (9.7 KB)

1 Like

You could use a Sprite Sheet instead. How to create a sprite sheet on roblox? - #2 by inHeadspace