Hi there. I’m trying to make so that when you touch any part within a model with a tool, it will check if the tool name equals to any value inside of my table. I have searched around for surely 1 hour but haven’t found anything that works with this (all touched events works perfectly, by the way)
local Tools = {"Sword", "Gun"}
for i,v in pairs(script.Parent.Model:GetChildren()) do
v.Touched:Connect(function(Touch)
if Tools[Touch.Parent] then
print("Works")
end
end)
end
If you could tell me how I can fix this, it’d be very appreciated! If anything is unclear, please tell me below.
Just tested this and this should work (you can make this a child of the model this applies to, or just specify where your model is located in the code):
local Model = script.Parent
local Tools = {"Sword", "Gun"}
for i, v in pairs (Model:GetChildren()) do
v.Touched:Connect(function(Touch)
if Touch.Parent:IsA("Tool") then
local Tool = Touch.Parent
for x, c in pairs (Tools) do
if c == Tool.Name then
print("Works")
end
end
else
return
end
end)
end
Your error just comes from the fact that you can’t access a table value by doing Table[value]. You have to specify the index if you’re doing it that way. You could have checked like
if Tools[1] == Touch.Parent.Name or Tools[2] == Touch.Parent.Name --// and so on and on, but this gets long...
In the snippet I just sent you what is basically happening is that we specify the model, create a table of its parts, parse through each part and tag an event onto it (this is exactly what you were doing) and then once the event is triggered check to see if whatever touched it is part of a tool (this could potentially lead to an error if the part isn’t a direct child of a Tool like if your tool has models or folders inside of it). If the part is indeed a child of a tool, we parse through the table of Tool names i.e. Tools that you defined earlier in the same way that we parsed through the parts of the model. Then we just check to see if the Name of the tool is equal to the strings in the table!
Let me know if that makes sense or if it’s not working as you expect!
Suggesting loops where not necessary is bad advice. Don’t misuse or abuse loops, use the proper ways of accomplishing this. Either you have the option of converting this to a dictionary or using table.find, but absolutely do not use loops here.