I would like to see examples of Collection Service in use

Hello, I have read the wiki page but it seems with the new wiki format, most or even all of the code samples are gone.

Specifically, the page on Collections Service here even reference code sample in the text, but nowhere on the page can they be found.

I am interested in learning, and code examples would be really helpful. If anyone has any samples or suggestions for further reading, or how to find the missing code samples on the wiki, i would super appreciate it.

Thanks!

6 Likes

Say you had a lava brick. You create a nice red part, and write a script inside it with:

script.Parent.Touched:connect(function(part)
    local humanoid = part.Parent:FindFirstChild("Humanoid")
    if humanoid then
        humanoid:TakeDamage(100)
    end
end)

You copy and paste the lava brick everywhere. Now you realize that your players aren’t dying to the lava if they have a ForceField (because you used TakeDamage). You now have to change every single lava brick’s script.

CollectionService solves this issue. Let’s try this scenario again.

You create a lava brick. Instead of putting a script inside it, you use Tiffany’s Tag Editor to tag it as “LavaBrick” (you can use CollectionService at runtime, this is just an example).

You then have ONE script in ServerScriptService with the code:

local CollectionService = game:GetService("CollectionService")

local function kill(part)
    local humanoid = part.Parent:FindFirstChild("Humanoid")
    if humanoid then
        humanoid.Health = 0
    end
end

for _,lavaBrick in pairs(CollectionService:GetTagged("LavaBrick")) do
    lavaBrick.Touched:connect(kill)
end
58 Likes

Wow this is an amazing feature, thanks for the sample.

I have the plugin for tagging parts and its really handy, but it seems odd to me that tagging is not a core function of Studio. Also is it possible to tag objects via a script and are there any other ways to manage tags besides the plugin?

Finally, does anyone know where are the code samples that were previously in the wiki have gone?

5 Likes

Yes, you can tag instances via scripts using the CollectionService:AddTag method.

3 Likes

Yes.

CollectionService:AddTag, ninja posted by Thundermaker300.

I’m not sure. Post CollectionService and anything else you find on #platform-feedback:documentation-requests

2 Likes

:wink: (speaking of that, why is there no ninja emote?)

3 Likes

I like the Examples above but let’s be honest, you can do any of that without using CollectionService just put the kill bricks in a Folder Called “KillBricks” and use one script to handle it.


https://gyazo.com/c4ce521d6cea6b65e6e3f4dee3e38bfd

Not bad but you can do that without CollectionService too.


https://gyazo.com/a8faf655216baba0b97c652598be2544

Great Example

Instead of using RemoteEvent:FireAllClients() you use that


https://gyazo.com/8c02e5c02b3134a37318593326fde664

CollectionService is really good for OOP

You can use this to create Events for your Objects but you can already do this by using Remote Objects and Bindable Objects

You can use it for detecting when something is Added and Destroyed. (I can’t really think of other uses tbh)

Note
https://gyazo.com/d8a5a22e11d8ee55527408564ea81986

When Written on Server it Replicates and ALL Clients will See the Changes.

When Written on Client On Client will See the Changes.


My use cases are

Using CollectionService to add Tags for something that you don’t want to store in a Script or Value Class Instances

Using CollectionService to add Tags for Signalling the Client instead of using a Remote Object

Using CollectionService to add Tags to “Radios” so when a Player decides to mute them it’s easy to do so.

Using CollectionService to add Tags to Players who are an Owner or Developer / VIP game pass Owner and when you hover your mouse over that person it displays a Text with “Owner”, “Dev” or “VIP”

Using CollectionService to add Tags to a TargetPlayer who is attacked by another Player so that when the TargetPlayer dies you know who did it, the only down side of this is that you can’t use DebrisService but you can use Delay instead to delete the Tag if needed.

Using CollectionService to add Tags to a NPC Monster so when it dies you know which player should get EXP and Money.


TLDR;

You can use it for Tagging Instances with a String instead of using a Script or RemoteObject, it also carries over from Studio to In-Game, so you can Pre-Tag stuff before the game is even played.
Tags will also carry on to a Duplicate or Copied Instance so you don’t have to add the tag again.


Bonus

@Planet_Dad Here’s the missing code sample from the “Old Wiki”

4 Likes

The original door example I wrote for the wiki is kind of bad honestly. I wrote it quickly when I noticed the wiki had no examples. I’ll talk to people on IX team about adding better examples.

I just wrote up a quick example which should be more understandable. It’s a full implementation, instead of handwaving out the actual code, and it relies less on language features new developers might not be familiar with such as metatables. It also has more detailed comments.

-- The sound to play while the bomb is ticking down
local tickSound = Instance.new("Sound")
tickSound.SoundId = "rbxasset://sounds/clickfast.wav"

-- The sound to play when the bomb explodes
local explodeSound = Instance.new("Sound")
explodeSound.SoundId = "rbxasset://sounds/Rocket shot.wav"
explodeSound.Volume = 1

-- Create a bomb object that handles ticking down and exploding
local function newBomb(instance)
	local bomb = {
		instance = instance,
		running = true,
	}

	function bomb:destroy()
		if self.tickSound then
			self.tickSound:Destroy()
		end
		if self.explodeSound then
			self.explodeSound:Destroy()
		end
		-- Stop the sequence if it's not too late
		self.running = false
	end

	function bomb:runSequence()
		self.tickSound = tickSound:Clone()
		self.tickSound.Parent = self.instance

		local timeToWait = 1.0
		local timeToShortenBy = 0.9
		for i = 1, 10 do
			wait(timeToWait)
			-- Bail out if the bomb was cancelled in time
			if not self.running then
				return
			end
			self.tickSound:Play()

			timeToWait = timeToWait * timeToShortenBy
		end

		-- Time to explode
		self.explodeSound = explodeSound:Clone()
		self.explodeSound.Parent = self.instance
		self.explodeSound:Play()

		local explosion = Instance.new("Explosion")
		explosion.BlastRadius = 12
		explosion.BlastPressure = 1000000
		explosion.Position = self.instance.Position
		explosion.Parent = workspace

		-- Lock the bomb in place while it's exploding
		self.instance.Anchored = true
		self.instance.CanCollide = false

		wait(1)

		-- Clean up the leftover bomb
		self.instance:Destroy()
	end

	-- Kick off the bomb sequence as soon as the bomb is created
	spawn(function()
		bomb:runSequence()
	end)

	return bomb
end

local CollectionService = game:GetService("CollectionService")
local bombTag = "Bomb"
-- An array that will contain all of our bomb objects
local bombObjects = {}

-- Whenever we add the bomb tag to an instance to make a new bomb, or add an object with the tag to the world, this will be called
local function bombTagAdded(instance)
	bombObjects[#bombObjects + 1] = newBomb(instance)
end

-- If we remove the bomb tag from an instance, or the instance is removed from the world, this will be called
local function bombTagRemoved(instance)
	for i = 1, #bombObjects do
		if bombObjects[i].instance == instance then
			-- Call the bomb:destroy() function from above
			bombObjects[i]:destroy()
			-- Remove it from the table
			table.remove(bombObjects, i)
		end
	end
end

-- Go through all the bombs already in the world
for _, instance in pairs(CollectionService:GetTagged(bombTag)) do
	bombTagAdded(instance)
end

-- Whenever a new bomb is added after the script runs, this signal will make sure we handle it
CollectionService:GetInstanceAddedSignal(bombTag):Connect(bombTagAdded)
-- When a bomb is removed
CollectionService:GetInstanceRemovedSignal(bombTag):Connect(bombTagRemoved)
16 Likes

This is a good example but I feel this is more fit for a “recipe” page than the one front and center on CollectionService, it is very lengthy if its goal is only to teach CollectionService.

6 Likes

Hello again, I am bringing up my thread again because I have been using the plugin by Tiffblocks and it is wonderful but I have a nagging question:

Where are the tags stored that I create with this plugin?

Normally we can add tags inside an part by using the method inside a script, like the examples on the wiki. But when I use this plugin, it just does it and I cant find where they are kept!

My concern is that if the plugin were to ever not work for some reason or other, or become obsolete, what would this mean for my development?

It just uses :AddTag. There’s a folder in ServerStorage with the names of the tags just for the GUI, but the tags are added as usual.

1 Like

ok but HOW, at runtime? I am looking inside the parts that I have tagged while in studio and theres no scripts inside them, so how can they be tagged?

Normally to tag a part, i would need to insert a script inside of it and use the method to do it. In this case there is no script inside each part, so where is the tag?

Also, if I uninstall the plugin, will this not work anymore?

I really just dont understand, thanks for helping!

All tags are serialized, they are not generated at runtime by the plugin.

1 Like

OK thanks, not sure what that amounts to? So they are translated to a string and stored… where?

Serialization has a definition in terms of general programming but in terms of implementation in the Roblox engine, what does that amount to?

If the plugin goes POOF, what happens to my game?

Thanks, sorry if I am being dense but this does not seem typical of anything else I have expereinced in the roblox engine.

They are saved for each instance. If you copy an object and put it into another file it’ll still have the tags that were assigned.

All the plugin does is visualizes the tags that you have in your file, and lets you easily add/edit them.

1 Like

The plugin just shows you a visual reference of all tags. When you add a tag with the plugin, it’s essentially the same as calling CollectionService:AddTag(). The tags aren’t stored in the plugin.

1 Like

I see, so without the plugin you could not possibly see what objects were tagged?

Seems like this should be a native part of Studio, and/or have the tags visualized in the Hierarchy or Properties somehow.

Starting to understand now. Thanks!

1 Like

Unless you have a namespace collision with tags, they are not dangerous on their own and a user may not need to know what items are tagged.

1 Like

It just adds them while you’re in Studio. When you publish, it keeps the tags. All Tag Editor does is provide an easy to use GUI.

Try this even if you don’t have the plugin installed:

  1. Open a baseplate
  2. Insert a part
  3. Enter in the command line: game.CollectionService:AddTag(workspace.Part, "Taggy")
  4. Publish
  5. Close and reopen
  6. print(game.CollectionService:HasTag(workspace.Part, "Taggy")
1 Like

all the doors lights alarms ect is controlled by collection service so take a look :slight_smile: Innovation Research Center [Beta] - Roblox
here are some screenshots

4 Likes