Problem with collectionservice

Hello once again, i’ve recently come across a weird problem with collectionservice when making these moving platforms, only one of them actually work and move around, the other one stays at its place, i’ve tried duplicating them and even with 4 only ONE works, and i have absolutely zero idea what it could be, i used this for stuff like raising platforms using tweenservice and it has worked completely fine.

image for reference:

script:

local collectionservice = game:GetService("CollectionService")

local moving = collectionservice:GetTagged("moving")

for _, plat in pairs(moving) do
	
	local waittime = plat.Value.Value

	local p1 = plat.Parent.p1
	print(plat.Parent)
	local p2 = plat.Parent.p2

	local ap = plat.AlignPosition

	local rope = Instance.new("RopeConstraint", p1)
	rope.Visible = true
	rope.Color = BrickColor.new(0, 0, 0)
	rope.Attachment1 = p1.rope1
	rope.Attachment0 = p2.rope0

	local distance = (p1.Position - p2.Position).Magnitude
	local velocity = distance / waittime + distance / waittime

	local pattach = p1:FindFirstChild("Attachment")
	ap.MaxVelocity = velocity

	while true do
		pattach.Parent = p2
		task.wait(waittime)
		pattach.Parent = p1
		task.wait(waittime)
	end
end 

Any help is appreciated.

It’s because you have a while true loop in your code. The code can’t carry on in the for loop because its waiting for the while true loop to finish, which it never will. Either use something such as RenderStepped or Heartbeat with RunService or create a new thread for the while loop.

2 Likes

Try creating a function that can be run for any moving part, and then call it for all existing moving parts and for any parts that are tagged during runtime.

local CollectionService = game:GetService("CollectionService")

-- function to run when an item with the "moving" tag is detected
local function movingAdded(plat)
	-- do something
end

-- detect when new moving parts are added
CollectionService:GetInstanceAddedSignal("moving"):Connect(movingAdded)

-- run for all currently existing moving parts
for i, plat in pairs(CollectionService:GetTagged("moving")) do
	task.spawn(movingAdded, plat) -- task.spawn to run asychronously so all platforms can run at once
end

actually, using coroutine.wrap fixed everything, thanks for the help to those who replied!