I am looking for some help with understanding how to detect a part being touched using the for i, v in pairs function.
I have a code for a racing server that has a function where the track wears down over time and changes color (similar to how a dirt road changes color in real life). I am trying to convert said script from the tires into a server script to help boost server performance.
The script works by having a track with thousands of parts on it, and when they are touched, they change color and lose friction (works fine). I would like to understand how to make it so when the parts are found and detected, they are individually changed when they are touched, not all at once.
If there is a smoother way of doing this besides the way I figured, let me know! Thanks!
If I understand your situation, you’re trying to find a way to loop through all of the parts in the track and detect whether there’s external parts that’s touching that part that’s not of the track. If so, IIRC, you could use Part:GetTouchingParts() for all of the parts within that loop (if that makes sense) to see if the part is being touched.
I’m not sure this is the best way of operation, unless you instead connect to a Part.Touched and run that loop once (So that it don’t create a bunch of function connections), but it should still work.
Something like this:
-- Using Part:GetTouchingParts()
-- Continuously going through the loop and checking
while game:GetService("RunService").Heartbeat:Wait() do
for i, part in pairs(Track:GetChildren())
-- if you didn't know:
-- i = name (pairs) // number/position (ipairs)
-- part = v = value
if #part:GetTouchingParts() > 0 then
-- Using Part.Touched
-- Only need to run the loop once
for i, part in pairs(Track:GetChildren()) do
It might be more optimal to use the Part.Touched, but that’s just me.
Again, it’s not like I was trying to make the best of the best scripts; it’s just to show how he might be able to script it… But I thank you for the input.
Also, for the last suggestion, I’m not sure where you see me using part:GetTouchingParts() as a loop but, that’s to check if there’s at least one part that’s touching that part in the GetTouchingParts() table.