Check When Something Touches a Part

Check When Something Touches a Part

Jun 14 2019, 4:48 PM PST


You want to execute some code when a Part is touched.


local part = Instance.new('Part')
part.Anchored = true
part.Parent = workspace
	print("Part was touched.")


The result of this is that when something touches the newly created part, “Part was touched” will be outputted. To see the result of the output open the output window from View --> Output.

As before, we create a new part, parent it to the Workspace, and anchor it. Events work in the following manner, you index (to find or get) the event (basically say object.Event), and then hook the event. This means that once this event happens it will trigger the function given. In order to hook an event, you must supply the callback function (the function that is called when the event is triggered) to the hooking method called connection.

This may sound confusing, but it is quite simple. An event is just as it sounds, its an event. Events are specific to an object, say for example there is an object called myObject. Let’s also say that there is the Clicked event when the object myObject is clicked. In order to get that event we do something like this: myObject.Clicked. In the case of the Part, and the Touched event, we do this: part.Touched in order to get the event. Now when the event is triggered or fires, we want to do something. In our case we printed Part was touched. when the part was touched. In order to do this we have to hook a callback function. The connect function allows us to do that like so: object.Event:connect(callback). Once the event occurs, callback will be called.

Some events pass the callback function arguments. For example, the Touched event passes the callback function the object which touched the original object.

  • events
  • touch
  • mechnic