For loop optimization

hey guys,

im looking into optimizing a function i have that changes multiple texture transparency’s in a for loop.

The script casts a ray every frame, and fires the function with the Enum.Material as the argument. (it will only fire the function if the material the part passes over has changed)

in the ChangeTexture function, it will check which material the part has passed over, then it will incrementally decrease the transparency of one texture, while increasing the transparency of the others.

function ChangeTexture(hit)
	local desc = workspace.Tank:GetDescendants()
	if Terrain == Enum.Material.Snow or Terrain == Enum.Material.Glacier or Terrain == Enum.Material.Ice then
		for i = 1,0,-0.001 do
			for index,v in pairs(desc) do
				if v.Name == 'Snow' and v:IsA('Decal') then
					v.Transparency = math.clamp(v.Transparency - 0.001,0,1)
				elseif v.Name ~= 'Snow' and v:IsA('Decal') then
					v.Transparency = math.clamp(v.Transparency + 0.001,0,1)
				end
			end
			task.wait()
		end
		
	end 
end

the script’s performance shoots way past 4%, and sometimes even reaches close to 20%.

maybe running loops within a loop to search and change the properties of over 100 textures isnt the most efficient way, so im asking here to see how you guys would do it, and to take some suggestions.

thank you!

A few solutions to mind.

  1. Maybe decrease the rate at which it changes, from 0.001 to 0.01, since changes under 0.001 will probably never be noticed and if you want to be performant I would suggest changing it.

  2. Store all the decals in a table and loop through that instead of looping through all the descendants and using selection. Especially if you have a big map.

  3. Use tweens instead, store them in a table and play them when you need to.

local DecalTweens = {}

local function LoadTweens(desc)
  for i,v in pairs(workspace:GetDescendants()) do
    if v:IsA('Decal') then
      local tween = TweenService:Create()
      DecalTweens[v] = tween
      -- etc
    end
  end
end

You could reduce -0.001 to something like -0.05, you won’t really notice the difference and it’s 50 times less loops.
Or you could use TweenService to change the transparencies.