Collection

Constructors

NameDescription
CollectionService:CreateCollection(query: string,root: Instance?):CollectionCreates a live, query-based Collection that tracks every instance matching the given selector query, rooted under root (defaults to Workspace). Called on CollectionService, not on Collection itself - Collection has no direct new() constructor.

Code Snippet

local CollectionService = game:GetService("CollectionService")

local collection = CollectionService:CreateCollection("Part.Flammable")

function collection.OnAdded(part)
    print(part.Name, "is now flammable")
end

function collection.OnRemoved(part)
    print(part.Name, "is no longer flammable")
end

function collection.OnTouched(part, otherPart)
    print(part.Name, "was touched by", otherPart.Name)
end

Properties

NameTypeDescription
EnabledbooleanWhether the collection is actively tracking instances and firing callbacks. Defaults to true. Setting this to false fires OnRemoved for every instance currently in the collection and stops all of its callbacks.

Methods

NameParametersReturnsDescription
ForEach(callback: function):voidcallback: functionVoidIterates over the instances currently in the collection, calling callback with each one. Operates on a snapshot taken at call time, so it is safe to add, remove, or destroy instances from within the callback.
Destroy():voidVoidVoidStops firing the collection's callbacks, releases the connections it manages on its members, and empties its set of instances. Also runs automatically when the collection's root instance is destroyed.