CollectionService Help

How can I make multiple Images spin at once?

This is my Server Script and the Tag is on all of the images I want to Rotate, and this script doesn’t work.

local CollectionService = game:GetService("CollectionService")

for _, SpinImages in pairs(CollectionService:GetTagged("SpinImage")) do
	while wait() do
		SpinImages.Rotation += 5
		if SpinImages.Rotation == 360 then
			SpinImages.Rotation = 0
		end
	end
end

Does anything happen at all? Have you tried printing the value of SpinImages to see if the issue lies in the for loop or the while loop?

Use ipairs instead of pairs. pairs is meant for dictionaries. :GetTagged() returns an array.

Also, I would recommend using a RunService.Heartbeat connection instead of a while wait() do loop.

That code works exactly how it’s supposed to. The problem is that while loops block subsequent code execution until they finish but your loop doesn’t break so it prevents the for loop from continuing on to the next iteration, meaning this will only ever spin for the first image.

There are a few ways to solve this problem:

  • Quick and dirty: use task.spawn to put the while loop onto a new coroutine.

  • Clean and proper: reverse the order of your loops. Your while should be on the outside, while the for is on the inside.

There’s some good optimisation tips from the above but a note on the first one is that you don’t have to use pairs or ipairs anymore since Luau supports generalised iteration.

-- {1, 2, 3} is a sample table
for index, value in {1, 2, 3} do
1 Like

Really? I’ve never heard of this. Could you provide some documentation on it, if it exists? I couldn’t find anything about it in the tables documentation. (I just wanna read more about it)

Luau Lang - Syntax: Generalized Iteration

1 Like