Hi, I am wondering if theres a better way of going about what I’m thinking I want to do. I want to create a not-so-easily-exploitable pick up system where a script scans the workspace for objects that have ClickDetector or whatever value I decide to use, and doesnt require any local scripts. Currently, this is the code I was able to come up with:
local objects = game.Workspace:GetDescendants()
local clickable = {}
for _, obj in ipairs(objects) do
if obj.ClassName == 'ClickDetector' then
table.insert(clickable, obj.Parent)
end
end
Is there a better way of going about this? I plan to also use the system for things like opening doors or opening loot gui’s of an enemies corpse, and I’m sure having the function loop through every workspace object and their children will cause a ton of lag. Is there a built in roblox method that can do something similar? Are there any known methods or even a better way than what I’m thinking of? Thank you for any help.
local CollectionService = game:GetService("CollectionService")
local tag = "AnyDescriptiveStringYouWant"
for _, object in pairs(CollectionService:GetTagged(tag)) do
-- do whatever you want with object
end
You can apply tags with CollectionService:AddTag(Object: Instance,Tag: String)
There are some decent user made plugins for applying tags too
I don’t know why they haven’t added a built-in tagging feature into studio… probably because they’re prioritizing other features.
Edit: I meant to say CollectionService, not SelectionService.
But on the topic of Selection Service, you can apply tags by selecting stuff in the explorer, then running this in the command bar:
local CollectionService = game:GetService("CollectionService")
local tag = "AnyDescriptiveStringYouWant"
local Selection = game:GetService("Selection")
for _, object in pairs(Selection:Get()) do
CollectionService:AddTag(object,tag)
end
Sorry, the objects or instances(idk what to call them) already have click decetors. I’m looking for a more efficient way of receiving those objects and running whatever code I need to on them.
Even if your spamming the code you sent it really won’t effect performance and honestly I wouldn’t go and do the Collection Service thing imo but yeah what you did is the way I would do it when checking for something that could be anywhere in the explorer. Theres really no “Better” way but people will give you alot of ideas that achieve the same result but this is already pretty simplified so no need.
local clickable = {}
for _,v in pairs(workspace:GetDescendants()) do
if v.ClassName == "ClickDetector" then
table.insert(clickable, v.Parent)
end
end
workspace.DescendantAdded:Connect(function(descendant)
if descendant.ClassName == "ClickDetector" then
table.insert(clickable, descendant.Parent)
end
end)
Yeah, honestly that’s what Im finding out right now. The function will only be ran once at world gen, and anything else I’ll just have ran through a different function.