CollectionService:GetInstanceAddedSignal firing twice

I am currently working on a fighting games where players fight players & non-player characters. I have some burning, freezing and other bunch of effects in my game that are getting added to specific targets by the use of CollectionService in one script, like this by example :

local function DizzyCalculation(BaseDamage,Character)
local Chance = math.random(1,100)
if Chance >= 50 and not CollectionService:HasTag(Character,"Dizzy") then
	CollectionService:AddTag(Character,"Dizzy")
	BaseDamage = BaseDamage*1.5
end
return BaseDamage

This works well, but in another script, I’m getting all the instances that are getting added to the workspace and I’m checking if they are a model with a humanoid inside of it, and if it’s the case, if a tag gets added to them, fire an event so that the effect will apply by itself, but it seems to fire twice for some unknown reason :thinking: :

local CollectionService = game:GetService("CollectionService")
local Settings = require(script.Settings)

local function StampEffect(Model,Effect)
	print("It seems like "..Model.Name.." has been "..Effect)
end

workspace.ChildAdded:Connect(function(Child)
	if Child:IsA("Model") and Child:FindFirstChild("Humanoid") then
		for _,Effect in pairs(Settings) do
			CollectionService:GetInstanceAddedSignal(Effect):Connect(function(Model)
				StampEffect(Model,Effect)
			end)
		end
	end
end) 

It’s printing the thing twice and it’s kinda annoying since I absolutely don’t know why in the world it would do that. I think that someone had the same problem : Double firing of CollectionService:GetInstanceAddedSignal when applying tag in same frame that object is added to DataModel.
Tried to read his post a few times, but I didn’t understand how he solved that so if you have an idea please tell me how to solve that issue?

It seems like the thread you linked was talking about when an instance is added to game at the same time that a tag is added to them, which is different from this scenario because an instance is added, and a tag listener is added to it.
I think the problem is just that you are creating an unnecessary amount of event listeners for new characters and NPCs in the game. You would only have to connect this event once for every effect, not for every model added to workspace as well.

e.g:

local function StampEffect(Model,Effect)
	print("It seems like "..Model.Name.." has been "..Effect)
end

for _,Effect in pairs(Settings) do
	CollectionService:GetInstanceAddedSignal(Effect):Connect(function(Model)
		StampEffect(Model,Effect)
	end)
end
2 Likes