Learn how to use events to make your scripts respond to player actions.
Events allow your code to respond when something happens in the game.
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.
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.
Prevent events from firing too quickly with 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.
Explore other useful events in Roblox.
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.
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.
Make a part that kills players when touched.
local killBrick = workspace.KillBrick
-- Write your code here
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)
Continue your learning journey