How should I make collision groups work as I want

Hello. I’m making a game where enemies can’t collide with players or it will break the game.

I’m currently doing this script.

local PhysicsService = game:GetService("PhysicsService")

local PlayersGroup = PhysicsService:CreateCollisionGroup('Players')
local EnimiesGroup = PhysicsService:CreateCollisionGroup('Enimies')

PhysicsService:CollisionGroupSetCollidable('Players','Enimies',false)

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		for _,v in pairs(character:GetChildren()) do
			if v:IsA("Part") or v:IsA("MeshPart") or v:IsA("UnionOperation") then
				PhysicsService:SetPartCollisionGroup(v,'Players')
			end
		end
		
	end)
end)

workspace.Enemies.ChildAdded:Connect(function(object)
	for _,v in pairs(object:GetChildren()) do
		if v:IsA("Part") or v:IsA("MeshPart") or v:IsA("UnionOperation") then
			PhysicsService:SetPartCollisionGroup(v,'Enimies')
		end
	end
end)

But it seems to works only for the last player added and last, enemie added.
Please tell me how could I fix this.

Have you checked within the collision group window, when you click on a part it’s collision group ID will be selected so you can make sure the script is properly setting the collision group within each part?

Otherwise try using Roblox’s method with an additional descendant added used it might be because of a Roblox package see within Detecting Collisions | Roblox Creator Documentation.

However, if any additional parts are added to the character after onCharacterAdded() has fired, such as a Tool or custom package, they will not belong to the same collision group as the character. In order to handle this, we can listen to the DescendantsAdded events on a character.