Script with loop Only Works on 1 object

So i have a script which generates falling leaves for each tree, and it works fine except one thing. it only loops on 1 tree and ignores other trees, that is probably because of my while true do loop, but i have no idea how to make loop work on other trees at the same time, any ideas how to fix that?

Script

local Tw = game:GetService("TweenService")

for _, v in pairs(workspace:GetDescendants()) do
	if v:GetAttribute("Leaves") and v:IsA("BasePart") then
		while task.wait(math.random(2, 6)) do
			local x = v.Position.X + math.random(-v.Size.X/2,v.Size.X/2)
			local y = v.Position.Y + math.random(-v.Size.Y/2,v.Size.Y/2)
			local z = v.Position.Z + math.random(-v.Size.Z/2,v.Size.Z/2)
			
			local Leaf = game.ReplicatedStorage:FindFirstChild("Leaf"):Clone()
				Leaf.Parent = workspace:FindFirstChild("Particles"):FindFirstChild("Leaves")
				Leaf.Color = v.Color
			Leaf.Position = Vector3.new(x, y, z)
			
			local RotationTw = Tw:Create(Leaf, TweenInfo.new(7, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, -1, true, 0), {Rotation = Vector3.new(360, 360, 360)})
			local MoveTw1 = Tw:Create(Leaf, TweenInfo.new(13, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, false, 0), {Position = Vector3.new(Leaf.Position.X, Leaf.Position.Y - 27.5, Leaf.Position.Z)})
			RotationTw:Play()
			MoveTw1:Play()
			
			while wait(0.05) do
				local TouchingParts = Leaf:GetTouchingParts()
				local Count = 0
				
				for i, TouchingPart in pairs(TouchingParts)	 do
					if not TouchingPart:GetAttribute("Leaves") then
						Count += 1
					end
				end
				
				if Count >= 1 then
					Tw:Create(Leaf, TweenInfo.new(1), {Transparency = 1}):Play()
					RotationTw:Pause()
					MoveTw1:Pause()
					task.wait(1)
					Leaf:Destroy()
					break
				end
			end
		end
	end
end

Use tags so every tree with a unique tag works with this script. After putting tags in all of the trees you want them to work the same you can get them from CollectionService: GetTagged(tag : string), and use same for loop to iterate through them.

but aren’t attributes are almost the same as tags? plus it already detects every tree but it goes through every of them but because of loop it stucks at first tree

I guess you can use any depending on the use case. This could help Attributes vs CollectionService.
In your case, v:GetAttribute(“Leaves”) does this work with just one tree?

It gets stuck because the first tree is yielding the running thread with the while loop you made. To counteract this, create a new task with task.spawn():

task.spawn(function()
    while true do
        --> leaf code here
    end
end)
2 Likes