Using collectionService for camera parts?

I am working on a game with a scriptable camera and was adding parts that act as regions that change the camera’s orientation, I recently heard about collectionService and thought, "Hey cool, now i don’t have to work with as many scripts but i realised that is not the case as i would still have to listen to the touched event and mess around with the tags more than i thought I’d have to, am i even using collectionService the right way? Or should i just stick with the touched event.

I think you should use a table for this.

Here’s some quick pseudocode

local cameraFunctions = {
    [workspace.Part1] = function()
        print('This is where it would do the camera function :)')
    end;
    [workspace.Part2] = function()
        print('camera function 2')
    end;
}
for i,v in pairs(cameraFunctions) do
    i.Touched:Connect(v)
end

If you want to do function types instead, you could probably use CollectionService for that, assuming there’s a way of knowing what function each part should connect to.

local functionTypes = {
    ['func1'] = function() print('1') end;
    ['func2'] = function() print('2') end;
    -- etc
}

for i,v in pairs(collectionService:GetTagged('cameraparts') do
    v.Touched:Connect(functionTypes[v:GetAttribute('FunctionType')])
end
1 Like

This would run the function for each part whenever one is touched?
I don’t understand
Ok i think i get it now, you just have to establish the connection once and it will run everytime after?

Yeah, you can always disconnect it too if you only want the part to be able to touched once as :Connect() returns a RBXScriptConnection value that can be disconnected at any time.

local connections = {}

local functionTypes = {
    ['func1'] = function() print('1') end;
    -- etc
}
for i,v in pairs(collectionService:GetTagged('cameraparts') do
    connections[v] = v.Touched:Connect(functionTypes[v:GetAttribute('FunctionType')])
    connections[v]:Disconnect() -- you could probably assign the connection to a variable if you just want it inside of the scope of this loop and nowhere else, it's just for example purposes
end
1 Like