--[[
PhysicsService:GetCollisionGroupName(playerCollisionGroupName)
PhysicsService:CollisionGroupSetCollidable(playerCollisionGroupName, playerCollisionGroupName, false)
]]


local previousCollisionGroups = {}

local function setCollisionGroup(object)
	if object:IsA("BasePart") or object:IsA("UnionOperation") then
		previousCollisionGroups[object] = object.CollisionGroup


		object.CollisionGroup = playerCollisionGroupName
		--PhysicsService:SetPartCollisionGroup(object, playerCollisionGroupName)
	end
end

local function setCollisionGroupRecursive(object)
	setCollisionGroup(object)

	for _, child in ipairs(object:GetChildren()) do
		setCollisionGroupRecursive(child)
	end
end

local function resetCollisionGroup(object)
	local previousCollisionGroup = previousCollisionGroups[object]
	if not previousCollisionGroup then return end 

	--local previousCollisionGroupName = PhysicsService:GetCollisionGroupName(previousCollisionGroupId)
	--if not previousCollisionGroupName then return end

	object.CollisionGroup = previousCollisionGroup
	--PhysicsService:SetPartCollisionGroup(object, previousCollisionGroupName)
	previousCollisionGroups[object] = nil
end

local function onCharacterAdded(character)
	setCollisionGroupRecursive(character)

	character.DescendantAdded:Connect(setCollisionGroup)
	character.DescendantRemoving:Connect(resetCollisionGroup)
end

local function onPlayerAdded(player)
	player.CharacterAdded:Connect(onCharacterAdded)
end

Players.PlayerAdded:Connect(onPlayerAdded)
