CollectionService doesn't get all the tagged parts

im making a drowning system using collectionservice, but when i playtest even tho all of the parts are tagged, only one works

i tried to put the code in loops but it still didnt work, and none of the posts on the dev forum helped

local CollectionService = game:GetService("CollectionService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local DAMAGE_PER_SECOND = 8
local TIME_BEFORE_DAMAGE = 3

for i, water in CollectionService:GetTagged("Water") do
	
	local inWater = {}
	
	water.Touched:Connect(function(object)
		if (object.Name == "Head" and inWater[object.Parent] == nil) then
			inWater[object.Parent] = TIME_BEFORE_DAMAGE
			ReplicatedStorage.Events.InWater:FireClient(game.Players:GetPlayerFromCharacter(object.Parent),true)
		end
	end)

	water.TouchEnded:Connect(function(object)
		if (object.Name == "Head") then
			ReplicatedStorage.Events.InWater:FireClient(game.Players:GetPlayerFromCharacter(object.Parent),false)
			local n = inWater[object.Parent]
			inWater[object.Parent] = nil
		end
	end)

	while (true) do
		for char, count in pairs(inWater) do
			if (count > 0) then
				inWater[char] -= 1
			else
				char.Humanoid:TakeDamage(DAMAGE_PER_SECOND)
			end
		end	
		task.wait(1)
	end
end


testing all the parts with the tag water, only one works

:sob:

It’s because you added a while true do loop inside the for loop. This loop will run forever which means that the for loop will always get stuck on the first water in the array (which is why only one works).

To fix this, wrap the while loop in a coroutine or use a different strategy.

--previous code
coroutine.wrap(function()
-- this isn't cpp or js, you don't need brackets
   while true do
		for char, count in pairs(inWater) do
			if (count > 0) then
				inWater[char] -= 1
			else
				char.Humanoid:TakeDamage(DAMAGE_PER_SECOND)
			end
		end	
		task.wait(1)
	end
end)
-- other code

You generally want to avoid infinite loops(they can be very unoptimized and there’s probably a better way).

Hope this helps!

1 Like

oh wow i forgot i added that
but thanks. it worked!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.