The Touched event fires when a part comes in contact with another part. For instance, if PartA bumps into PartB, then PartA.Touched fires with PartB, and PartB fires with PartA.
This event only fires as a result of physics movement, so it will not fire if the CFrame property was changed such that the part overlaps another part. This also means that at least one of the parts involved must not be
/BasePart/Anchored at the time of the collision.
Many types of parts are removed or destroyed as soon as they hit another part. This means that it is possible for the other part’s
/Instance/Parent to be nil. Be sure to check that
otherPart.Parent is not nil before using it, such as calling
The other part that came in contact with the given part.
This code sample demonstrates how to connect the Touched event of multiple parts in a Model to one function.
local model = script.Parent local function onModelTouched(part) -- Filter any instances of the model coming in contact with itself if part:IsDescendantOf(model) then return end print(model:GetFullName() .. " was touched by " .. part:GetFullName()) end for _, child in pairs(model:GetChildren()) do if child:IsA("BasePart") then child.Touched:Connect(onModelTouched) end end
Touching Parts Count
This code sample creates a BillboardGui on a part that displays the number of parts presently touching it.
local part = script.Parent -- Create a BillboardGui local bbgui = Instance.new("BillboardGui", part) bbgui.Size = UDim2.new(0, 200, 0, 50) bbgui.Adornee = part bbgui.AlwaysOnTop = true local tl = Instance.new("TextLabel", bbgui) tl.Size = UDim2.new(1, 0, 1, 0) tl.BackgroundTransparency = 1 local numTouchingParts = 0 local function onTouch(part) print("Touch started: " .. part.Name) numTouchingParts = numTouchingParts + 1 tl.Text = numTouchingParts end local function onTouchEnded(part) print("Touch ended: " .. part.Name) numTouchingParts = numTouchingParts - 1 tl.Text = numTouchingParts end part.Touched:Connect(onTouch) part.TouchEnded:Connect(onTouchEnded)
This code sample causes a part to blink its Reflectance and a PointLight every time it is touched. It uses a pattern that prevents multiple concurrent function calls from fighting with each other.
local part = script.Parent -- Add a light local pointLight = Instance.new("PointLight", part) pointLight.Brightness = 0 pointLight.Range = 12 local touchNo = 0 local function blink() -- Advance touchNo to tell other blink() calls to stop early touchNo = touchNo + 1 -- Save touchNo locally so we can tell when it changes globally local myTouchNo = touchNo for i = 1, 0, -.1 do -- Stop early if another blink started if touchNo ~= myTouchNo then break end -- Update the blink animation part.Reflectance = i pointLight.Brightness = i * 2 wait(0.05) end end part.Touched:Connect(blink)