How it Works
Simple and effective, but how does it work? Let’s explore the script step by step:
The first line just sets a variable that tells the script what specific game part it’s linked to. In this case it’s linked to the trap part, the “parent” of the script.
local trapPart = script.Parent
The next part is a function. In game scripts, functions are sets of related steps which can be used over and over.
local trapPart = script.Parent
local function onPartTouch(otherPart)
The code on line 4 includes a Parent and Child relationship. We also create a variable called “humanoid”, which looks for a player touching the trap part.
local function onPartTouch(otherPart)
local partParent = otherPart.Parent
local humanoid = partParent:FindFirstChildWhichIsA(“Humanoid”)
Create an If Then Statement
An if statement is a programming conditional statement that, if proved true, performs a function or displays information. This function checks if a careless player (not some other random part in the world) touched the trap. If so, it sets the player’s health to 0 which instantly destroys them.
local trapPart = script.Parent
local function onPartTouch(otherPart)
local partParent = otherPart.Parent
local humanoid = partParent:FindFirstChildWhichIsA(“Humanoid”)
if humanoid then
— Set player’s health to 0
humanoid.Health = 0
End Statement and onPartTouch
We always use end statements indented at the end of our code to tell the program to stop running code up to that point. The final line connects the trap part and the function with a Touched event. That makes the function run whenever the trap part is touched.
local trapPart = script.Parent
local function onPartTouch(otherPart)
local partParent = otherPart.Parent
local humanoid = partParent:FindFirstChildWhichIsA(“Humanoid”)
if humanoid then
— Set player’s health to 0
humanoid.Health = 0
end
end
trapPart.Touched:Connect(onPartTouch)