advanced
25 min

Events & Callbacks

Learn how to use events to make your scripts respond to player actions.

Touched EventsPlayer EventsCustom Events

1
Understanding Events

Events allow your code to respond when something happens in the game.

Touched Event

local part = workspace.Part

part.Touched:Connect(function(hit)
  print("Something touched the part!")
  print("It was: " .. hit.Name)
end)

Touched fires when any part touches this part. The hit parameter is the touching part.

Detecting Players

local part = workspace.DoorTrigger

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

Check if the touching object has a Humanoid to determine if it's a player character.

💡 Tips:

  • • Touched can fire multiple times rapidly
  • • Always check if objects exist before using them
  • • Use debounce to prevent spam

2
Debouncing

Prevent events from firing too quickly with debounce.

Simple Debounce

local part = workspace.Button
local debounce = false

part.Touched:Connect(function(hit)
  if debounce then return end
  
  local character = hit.Parent
  local humanoid = character:FindFirstChild("Humanoid")
  
  if humanoid then
    debounce = true
    print("Button pressed!")
    wait(2)  -- Cooldown
    debounce = false
  end
end)

The debounce variable prevents the event from triggering during cooldown.

3
Other Common Events

Explore other useful events in Roblox.

ChildAdded & ChildRemoved

workspace.ChildAdded:Connect(function(child)
  print("New object added: " .. child.Name)
end)

workspace.ChildRemoved:Connect(function(child)
  print("Object removed: " .. child.Name)
end)

These fire when objects are added or removed from containers.

Changed Event

local humanoid = character:WaitForChild("Humanoid")

humanoid.HealthChanged:Connect(function(health)
  print("Health is now: " .. health)
end)

humanoid.Died:Connect(function()
  print("Player died!")
end)

Monitor property changes and special events like death.

Practice Exercises

Exercise 1: Create a Kill Brick

Make a part that kills players when touched.

Starter Code:

local killBrick = workspace.KillBrick

-- Write your code here
Show Solution
local killBrick = workspace.KillBrick

killBrick.Touched:Connect(function(hit)
  local character = hit.Parent
  local humanoid = character:FindFirstChild("Humanoid")
  
  if humanoid then
    humanoid.Health = 0
  end
end)

Ready for more?

Continue your learning journey

Executors.Online - Your Roblox Developer Hub