Tween to constantly make things fade into random colors

(workspace replaced for a folder to represent it works)

not sure if its a cleaner solution (its longer, but i think more readable) but an alternative approach anyways

local Name, Collection, Tween, Info, Active, Tmp = script.Name, game:GetService("CollectionService"), game:GetService("TweenService"), TweenInfo.new(1, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut), {}, {}

local disconnectFunctions = {}
function color(part)
	local tween
	local ancenstryChanged
	local coreLoop
	
	local function coreLoopFunc()
		return task.spawn(function()
			while true do
				if not tween then
					tween = Tween:Create(part, Info, {
						Color = BrickColor.Random().Color
					})
				end
				tween:Play()
				tween.Completed:Wait()
				tween = nil
			end
		end)
	end
	
	local function pauseTween()
		if tween then tween:Pause() end
		if coreLoop then task.cancel(coreLoop) end
	end
	
	local function playTween()
		coreLoop = coreLoopFunc()
	end
	
	local function onRemove()
		if tween then tween:Cancel() end
		if coreLoop then task.cancel(coreLoop) end
		if ancenstryChanged then ancenstryChanged:Disconnect() end
	end
	
	local function smartPlay()
		if workspace:IsAncestorOf(part) then
			playTween()
		else
			pauseTween()
		end
	end
	
	-- not sure if collections auto garbage collect that's why im assigning it to ancenstryChanged
	ancenstryChanged = part.AncestryChanged:Connect(smartPlay)
	
	smartPlay()
	
	return onRemove
end

function instanceAdded(part)
	local disconnectFunction = color(part)
	disconnectFunctions[part] = disconnectFunction
end

Collection:GetInstanceRemovedSignal(Name):Connect(function(part)
	local disconnectFunction = disconnectFunctions[part]
	if disconnectFunction then
		disconnectFunction()
		disconnectFunctions[part] = nil
	end
end)

for i, part in Collection:GetTagged(Name) do
	instanceAdded(part)
end

Collection:GetInstanceAddedSignal(Name):Connect(instanceAdded)
1 Like