Hello! I am learning scripting so far so I wanted to make a trap that if you touched it will kill you but at the same time if you waited for a few seconds you can step on it without dying.
I tried to make it but there is a problom that I don’t know how to fix.
I am beginner at this and I am sorry for my bad english.
Here is my script
local part = script.Parent
local function trap(touchedplayer)
part.BrickColor = BrickColor.new("Really red")
if part.Touched then
local player = touchedplayer.parent
humanoid = player:FindFirstChild("Humanoid")
if humanoid then
humanoid.Health = 0
end
end
end
local function safe()
part.BrickColor = BrickColor.new("Lime green")
end
while true do
trap()
wait(2)
safe()
wait(2)
end
You have to somehow have different states within your program. There are quite a few ways to do this, such as with a flag:
local part = script.Parent
local isEnabled = false
part.Touched:Connect(function(hit)
local humanoid = (isEnabled and hit.Parent:FindFirstChild("Humanoid")) -- if isEnabled is false, it won't look for the humanoid
if humanoid then
humanoid.Health = 0
end
end)
while true do
isEnabled = not isEnabled -- Flip the flag between true and false
part.BrickColor = BrickColor.new(if isEnabled then "Really red" else "Lime green")
task.wait(2)
end
Or you could do the more “correct” way of disconnecting when the brick is inactive:
local part = script.Parent
local function trap(hit)
local humanoid = hit.Parent:FindFirstChild("Humanoid")
if humanoid then
humanoid.Health = 0
end
end
local connection = part.Touched:Connect(trap)
while true do
part.BrickColor = BrickColor.new(if connection.Connected then "Really red" else "Lime green")
task.wait(2)
if connection.Connected then
connection:Disconnect()
else
connection = part.Touched:Connect(trap)
end
end
It might be a lot to look at, but this is how you have to do it in some capacity (ignoring some shortcuts I took).