Hey DevForum! I’m working on learning the Roblox CollisionGroups feature.
local function onPlayerAdded(player)
local function onCharacterAdded(character)
setCollisionGroup(character, redPlayers)
end
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)
How would I adapt this code to assign players on join to the “redPlayers” collision group, to assign them to the respective collision groups when changing the player’s team?
I’m trying to assign teams with Adonis at the moment, on join, players are automatically added to spectators, then I team them manually, problem is, I don’t know how to make the team change correspond with adding them to or removing them from a CollisionGroup.
Just register some more events! We want to set collision group on
All descendants
Whenever a new descendant is added to the character (tool, et cetera)
local function setCollisionGroup(character)
local function handleDesendant(child)
if child:IsA("BasePart") then
PhysicsService:SetPartCollisionGroup(child, "RedTeam")
end
end
for _, item in pairs(character:GetDescendants()) do
handleDesendant(item)
end
-- NOTE: Might want to listen to descendants removing, and unset the collision group. Depends on your game, it may not matter.
return character.DescendantAdded:Connect(handleDesendant)
end
local function onPlayerAdded(player)
local conn = nil
local function onCharacterAdded(character)
if conn then
conn:Disconnect()
conn = nil
end
conn = setCollisionGroup(character, redPlayers)
end
-- Probably should also disconnect this connection, and also `conn` here
-- This boi memory leaks
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Note that the example you have memory leaks a bit. I’d go checkout Maids