✓ Accepted answer
The above code works but in terms of efficiency and professionalism, it completely lacks that. Since using Loops is an important skills as suggested by theCJarmy7, I will be teaching you basics of it and teach you how to implement it to other codes.
What is loops?
Loops are basically a set of code that repeats either certain amount of times, or infinitive. There are particularly three types of Loops
- While true do Loop
- For Loop
- Repeat..Until Loop
1) What is While true do 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.
Warning! Always end an infinite loop or add a wait() or else the code will crash your game!
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)
2) What is For loop ?
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)
3) What is Repeat Loop ?
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)
####Hope you learned something from this.
#####Have a lovely day of coding
1 comment
So you want me to hurt you just once?