In my game there are a bunch of players and vehicles that are supposed to be damaged when a bullet or an explosion hits them. All damagable models are indexed using CollectionService and I want to figure out if a part is a descendant of one of these models.
My current way of figuring this out would be:
for i,v in pairs(game.CollectionService:GetTagged("Damagable") do
if TestObject:IsDescendantOf(v) then
-- do stuff
end
end
What is the issue? (Keep it simple and clear - Include screenshots/videos/GIFs if possible)
This seems really inefficent so I wonder if there’s a faster way.
Your other options seem to be mainly adding the tag to all parts in the damage-able model or to navigate to part’s most-upper model parent, in both cases using CollectionService | Documentation - Roblox Creator Hub. Whether either of those are actually more efficient is up to testing it though. Do you have a reason to question (and feel the urge to improve) the efficiency in the current setup?
So from the code you posted, I presume that you take the object that is affected by the bullet and explosion, check whether the object has a parent with a Damagable tag and from that they’d continue.
This all really depends on the way your damagable objects are layed out. Do they have multiple Models/Folders to categorise parts and similar? If so, then you are best to use your method above. The cons with the method is if you have loads of objects in the game, you may be iterating through a lot each time and that’ll slow down each attempt to damage it (hopefully not by alot though)).
However, if all your destroyables were laid out in a similar way you could do something like this:
if game.CollectionService:HasTag(TestObject.Parent,"Damagable") then
-- attempt stuff
end
This would remove the need for looping through all the objects, but will require setting up for your destroyables. Assuming you have vehicles, they are most likely models sorted into the essentials and the “body” of the car. (But this doesn’t stop you doing an or statement.
All the things posted here are very helpful. A further optimization I thought of is to only check objects on the enemy team if the game doesn’t have team-killing.