PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

CreateCollisionGroup

Creates a new collision group with the given name, and returns the id of the created group.

Parameters

Name Type Default Description

Returns

Return Type Summary

int


Code Samples


PhysicsService:GetCollisionGroupId1

This example demonstrates one basic use of collision groups.

The code below attempts to get a group named “Test”, and creates a group this group if it does not already exist. Then, it sets a BasePart|part named Part1’s collision group to “Test”.

If this group is the first collision group you’ve made in your game, it’s Id will be 1.

Parts in the same collision group will interact with other collision groups and with each other a predetermined way. Collision groups can be collidable or not collidable - as set by PhysicsService/CollisionGroupSetCollidable and checked by PhysicsService/CollisionGroupsAreCollidable.

local physicsService = game:GetService("PhysicsService")

-- returns a valid group id (int) or nil
function getGroupId(name)
	-- GetCollisionGroupId will throw if it does not exist
	local ok, groupId = pcall(physicsService.GetCollisionGroupId, physicsService, name)
	return ok and groupId or nil
end

-- returns a valid group id (int) or nil
function getOrCreateGroupId(name)
	local ok, groupId = pcall(physicsService.GetCollisionGroupId, physicsService, name)
	if not ok then
		-- Create may fail if we have hit the maximum of 32 different groups
		ok, groupId = pcall(physicsService.CreateCollisionGroup, physicsService, name)
	end
	return ok and groupId or nil
end

-- sets the specified part's collision group to the group with 
-- given group id
function setPartCollisionGroup(part, name)
	physicsService:SetPartCollisionGroup(part, name)
end

-- returns the id of part's collision
function getPartGroupId(part)
	return part.CollisionGroupId
end

	
print("Get 'Test' Group:", getGroupId("Test")) -- prints nil
print("Get/Create 'Test' Group:", getOrCreateGroupId("Test")) -- prints 1
print("Get Id of 'Test' Group:", getGroupId("Test")) -- prints 1
print("Setting Part1's collision group...")
setPartCollisionGroup(game.Workspace.Part1, "Test")
print("Part1's Collision Group Id:", getPartGroupId(game.Workspace.Part1)) -- prints 1