Skip to content

Commit 9e585be

Browse files
authored
Optimization of Collision Group Script: Removed DescendantAdded Connection for Improved Performance
I've optimized the script for handling collision groups in Roblox. The main change involves removing the connection to DescendantAdded, applying the collision group immediately to all parts in the model upon character addition. This reduces unnecessary event connections, improving performance by applying the collision group once for all descendants, rather than repeatedly when new parts are added. This should help improve game performance, especially when handling many parts or players.
1 parent e6a1e01 commit 9e585be

File tree

1 file changed

+18
-18
lines changed

1 file changed

+18
-18
lines changed

content/en-us/workspace/collisions.md

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -262,27 +262,27 @@ interesting but unintended gameplay, such as characters jumping on top of each o
262262
local PhysicsService = game:GetService("PhysicsService")
263263
local Players = game:GetService("Players")
264264

265-
PhysicsService:RegisterCollisionGroup("Characters")
266-
PhysicsService:CollisionGroupSetCollidable("Characters", "Characters", false)
267-
268-
local function onDescendantAdded(descendant)
269-
-- Set collision group for any part descendant
270-
if descendant:IsA("BasePart") then
271-
descendant.CollisionGroup = "Characters"
272-
end
273-
end
274-
275-
local function onCharacterAdded(character)
276-
-- Process existing and new descendants for physics setup
277-
for _, descendant in character:GetDescendants() do
278-
onDescendantAdded(descendant)
279-
end
280-
character.DescendantAdded:Connect(onDescendantAdded)
265+
local CollisionGroupName = "Characters"
266+
PhysicsService:RegisterCollisionGroup(CollisionGroupName)
267+
PhysicsService:CollisionGroupSetCollidable(CollisionGroupName, CollisionGroupName, false)
268+
269+
local function setCollisionGroup(model)
270+
-- Apply collision group to all existing parts in the model
271+
for _, descendant in pairs(model:GetDescendants()) do
272+
if descendant:IsA("BasePart") then
273+
descendant.CollisionGroup = CollisionGroupName
274+
end
275+
end
281276
end
282277

283278
Players.PlayerAdded:Connect(function(player)
284-
-- Detect when the player's character is added
285-
player.CharacterAdded:Connect(onCharacterAdded)
279+
player.CharacterAdded:Connect(function(character)
280+
setCollisionGroup(character)
281+
end)
282+
-- If the player already has a character, apply the collision group immediately
283+
if player.Character then
284+
setCollisionGroup(player.Character)
285+
end
286286
end)
287287
```
288288

0 commit comments

Comments
 (0)