I want to run the same OnTouch Function on multiple parts with one script, how would i go about doing this? I also need to determine what part was touched in the universal function.
When the part gets touched it upgrades the level of a model. I need to be able to determine what part was touched so i can get the price value of the upgrade.
Breakdown: How can I do this?
for a, b in ipairs(parts:GetChildren()) do
b.Touched:Connect(Touch)
end
Just create the your logic of your own function, then use a for loop to get all of the parts, then connect them to an event along with the function you just made.
-- Touch returns a function that is used for .Touched
local function Touch(part)
-- part is the original part
return function(hit)
-- hit is the part that collided that was moving
end
end
for a, b in ipairs(parts:GetChildren()) do
b.Touched:Connect(Touch(b)) -- call it with the original part which returns a function
end
local partsFolder = workspace:WaitForChild("PartsFolder") -- Contains the parts that we'd want to connect the touch event with
for _, part in pairs(partsFolder:GetChildren()) do -- Looping through the folder using pairs. ipairs is just an index pair (loops in order perfect for arrays)
if (part:IsA("BasePart")) then -- Checks if the part is a basepart, could accidentally get an invalid instance in there
part.Touched:Connect(function(hit) -- Connect the RBXSignalConnection, Touched, to a function.
-- Continue code here or you could use callback function instead of an anonymous
end)
end
end
Good practise for this, due to the unsafe nature of the part.Touched() I recommend doing checks on the server to check if the humanoid, player, is within close proximity to the part that has the event on it. This is because the Touched Event uses the client’s position to decrease latency for a smoother experience, this comes at a cost for security. This means that the client could lie about their position and give false positions, firing touched events from miles away.
local parts = workspace.Model:GetChildren()
function Touched(p1, p2)
print(p1, p2) --p1 is the "owner" of the event
end
for _,v in pairs(parts) do
v.Touched:Connect(function(p) Touched(v, p) end)
end