Hello everyone! I have made a lantern model, and thought it would be cool if I made it that any time a lantern is touched it smashes! I want to have only one script that will run all this and not have a script in each lantern. How would I do this. This is what I have tried.
You could use CollectionService,
Tag each lantern with the “Lantern” tag and use CollectionService:GetTagged(“Lantern”)
You can use this plugin to tag objects: Tag Editor
e.g.
local CollectionService = game:GetService("CollectionService")
for k, lantern in pairs(CollectionService:GetTagged("Lantern")) do
lantern.Touched:Connect(function()
lantern:BreakJoints()
end)
end
CollectionService | Roblox Creator Documentation can be great for this.
I have more info on the ways it can be used here:
But the docs page also has some great examples at the bottom about how to use it for a door.
So, is my code right, or did I do something wrong with it? if its right I feel like it should work.
Yes, it will work but using CollectionService is better
The reason because it isn’t working is that this script will be run when you press play so just one time as @majdTRM and @nicemike40 said use the collection service or use a while loop if you prefer.
But it isn’t working this way either.
Are you dynamically creating these lanterns, or just one-time? (In studio only)
I am only creating them one time.
Then I don’t see why this isn’t working. Did you tag each lantern with the plugin I mentioned?
I haven’t tried using the collection service yet. I was saying it isn’t working without it like you said it would. I will try it with collection service now.
Make sure each lantern is named “Lantern”
(For the original method)
you can try using :GetChildren() instead of getdescendants
and where is your script located?
BTW, by one-time, do you mean through a script, or in studio? And are they all named “Lantern”? (Without quotes)
I mean one time in studio. Yes they are all named Lantern.
I think you can’t do .Touched on a model, only a part.
Try creating an invisible bounding box and do .Touched on that.
for k, lantern in pairs(workspace:GetDescendants()) do
if lantern.Name == "Lantern" then
lantern.Bounds.Touched:Connect(function() -- <== Changed code here
lantern:BreakJoints()
end)
end
end
Alternate solution:
for k, lantern in pairs(workspace:GetDescendants()) do
if lantern.Name == "Lantern" then
for k, part in pairs(lantern:GetDescendants()) do -- I don't know if all the parts are top-level
if not part:IsA("BasePart") then
return
end
lantern.Bounds.Touched:Connect(function() -- <== Changed code here
lantern:BreakJoints()
end)
end
end
end
If that worked, then try CollectionService
YES!!! IT WORKED!!! Now I will try it with collection service.