I had an issue where I had multiple physical bricks in a game to prompt a gamepass purchase via a Touched Event. I decided it would be a good time to learn to use module scripts since I had heard this is one of the use cases for them. However I found myself just gravitating to the method of
for i, Brick in pairs(TouchParts:GetChildren())
** Brick…Touched:Connect(function))**
** end)**
end)
Is this bad practice? Or are the methods interchangeable. Perhaps module scripts are more effecient time wise. Or maybe theres more features to module scripts that im aware of.
I would say if you don’t need to use Module script then don’t try to force it. No reason to over complicate a simple system if it works for what you need.
If all the bricks are in one folder/model, then the simple loop might make the most sense.
If so, an example from my game is that I made a ‘gamechat’ module script that has functions to post messages to the chat dialog box. So, any script that I want to be able to trigger chat messages based on events that happen in the script, i just ‘require’ the module script and i have access to the function to ‘say message’ to the chat.
I did that so I don’t have to copy and past that chat ‘stuff’ in each script that needs to be able to post a chat message.
ModuleScripts are great for reusing code. However, you probably want to use tags instead for this. Tags let you attach new functionality to your parts.
Here’s the example code for a death brick that I copied from the documentation. Try refitting this to your needs:
local CollectionService = game:GetService("CollectionService")
local tag = "Deadly"
local function onDeadlyPartTouched(otherPart)
if not otherPart.Parent then
return
end
local human = otherPart.Parent:FindFirstChildOfClass("Humanoid")
if human then
human.Health = 0
end
end
-- Save the connections so they can be disconnected when the tag is removed
-- This table maps BaseParts with the tag to their Touched connections
local connections = {}
local function onInstanceAdded(object)
-- Remember that any tag can be applied to any object, so there's no
-- guarantee that the object with this tag is a BasePart.
if object:IsA("BasePart") then
connections[object] = object.Touched:Connect(onDeadlyPartTouched)
end
end
local function onInstanceRemoved(object)
-- If we made a connection on this object, disconnect it (prevent memory leaks)
if connections[object] then
connections[object]:Disconnect()
connections[object] = nil
end
end
-- Listen for this tag being applied to objects
CollectionService:GetInstanceAddedSignal(tag):Connect(onInstanceAdded)
CollectionService:GetInstanceRemovedSignal(tag):Connect(onInstanceRemoved)
-- Also detect any objects that already have the tag
for _, object in pairs(CollectionService:GetTagged(tag)) do
onInstanceAdded(object)
end