Understanding On Touch Logic

Touch events are an integral part of creating interactive experiences in Roblox. This section covers the basics of how to detect and respond to touch events in your game. With a few lines of code, you can create engaging interactions, like detecting when players activate buttons, touch obstacles, or pick up items.

What is a Touch Event?

A Touch Event occurs when an object (like a player or part) comes into contact with another part in the game. The Touched event allows developers to respond to these interactions, triggering specific behaviors like playing sounds, starting animations, or displaying messages.

Basic Touch Event Script

Here's an example of a basic touch event script that prints the name of the object touching the part:

  1. Insert a Part into your workspace and name it TouchPart.
  2. Insert a Script into the part.
  3. Paste the following code into the script:

local part = script.Parent
part.Touched:Connect(function(hit)
    print(hit.Name .. " touched the part!")
end)
                

How It Works

In this script:

Advanced Touch Event Example

Want to make something happen when a player touches the part? Here's an example that detects if the object touching the part is a player:

  1. Insert a Part into your workspace and name it TriggerPart.
  2. Insert a Script into the part.
  3. Use the following script:

local part = script.Parent

part.Touched:Connect(function(hit)
    local character = hit.Parent
    local player = game.Players:GetPlayerFromCharacter(character)
    
    if player then
        print(player.Name .. " touched the part!")
    end
end)
                

What's New in This Script?

Tips for Using Touch Events

Real-World Applications