CollectionEvents - Cleanly connect events on a per tag basis

CollectionEvents
by emperormicah

Easily connect events to tags :)
Disconnects when tags are removed :)

Docs:

CollectionEvents.Tag.Event:Connect(function func)
where any instance with tag Tag has event Event, func is passed events args

CollectionEvents.Tag.Event:ConnectWithPassthrough(function func)
where any instance with tag Tag has event Event, func is passed object, events args

CollectionEvents.Tag.Event:ConnectAndForget(function func)
where any instance with tag Tag has event Event, func is passed events args
no reference to connections afterwards
using this method, if you remove tag there is no cleanup
if you remove then add a tag again, there will be duplicate event connections

All three methods return a maid.

Example 1: kill players who touch parts tagged with “Lava”

local CollectionEvents = require(...)

CollectionEvents.Lava.Touched:Connect(function(hit)
	if hit.Parent then
		local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid")
		if humanoid then
			humanoid.Health = 0
		end
	end
end)

Example 2: damage players who touch parts tagged with “Lava”, by Damage attribute of part

local CollectionEvents = require(...)

CollectionEvents.Lava.Touched:ConnectWithPassthrough(function(basepart, hit)
	local damage = basepart:GetAttribute("Damage")
	if hit.Parent and damage and type(damage)=="number" then
		local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid")
		if humanoid then
			humanoid:TakeDamage(damage)
		end
	end
end)

Model:

4 Likes