I'm trying to build a brick that when you touch it it only takes some damage but will continue to that same amount every few seconds while the player is on the brick.
function onTouched(hit) local h = hit.Parent:findFirstChild("Humanoid") if (h ~= nil) then h.Health = h.Health - 6 wait(3) end end script.Parent.Touched:connect(onTouched)
I tried this script but it will not continue to take damage when the player is standing still.
Loops are basically a set of code that repeats either certain amount of times, or infinitive. There are particularly three types of Loops
1) While true do Loop
2) For Loop
3) Repeat..Until Loop
A While True Do
loop is a type of loop that runs a set of code infinite times until the condition is false
. Here is how you would loop your code using the While true do.
function onTouched(hit) local h = hit.Parent:findFirstChild("Humanoid") while true do if (h ~= nil) then h.Health = h.Health - 6 wait(3) end end end script.Parent.Touched:connect(onTouched)
For loop is another type of loop which, unlike while true do loop, it only runs the code certain times, explicitly defined by the programmer. I will take the example using MrLordFearLT's code.
local function PlayerTouched(Part) local Parent = Part.Parent if game.Players:GetPlayerFromCharacter(Parent) then for number = 100, 0, -10 do Parent.Humanoid.Health = number wait(3) end end end Brick.Touched:connect(PlayerTouched) -- Look at that! We wrote that long code in such short place.
Repeat loop is the last type of the loops which repeats the code block until the condition has been met. Again, let's use your code as an example.
function onTouched(hit) local h = hit.Parent:findFirstChild("Humanoid") repeat h.Health = h.Health - 6 wait(3) until h.Health == 0 end script.Parent.Touched:connect(onTouched)
Hi There Im not best at scripting im beginner too My Roblox Username MrLordFearLT if you want to invite me:D here i builded script for you u can change lines where wait(number) and how much player will have health per second Script --Variables-- local Brick = script.Parent --End--
--Code--
local function PlayerTouched(Part) local Parent = Part.Parent if game.Players:GetPlayerFromCharacter(Parent) then Parent.Humanoid.Health = 90 wait(1) Parent.Humanoid.Health = 80 wait(1) Parent.Humanoid.Health = 70 wait(1) Parent.Humanoid.Health = 60 wait(1) Parent.Humanoid.Health = 50 wait(1) Parent.Humanoid.Health = 40 wait(1) Parent.Humanoid.Health = 30 wait(1) Parent.Humanoid.Health = 20 wait(1) Parent.Humanoid.Health = 10 wait(1) Parent.Humanoid.Health = 0 wait(1) end end Brick.Touched:connect(PlayerTouched)
Insert In part Named Part and add in Part Script and copy this script to Script Document.. Have A good day! u can response me if you want.