Answered by
7 years ago Edited 7 years ago
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
1) While true do Loop
2) For Loop
3) 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!
01 | function onTouched(hit) |
02 | local h = hit.Parent:findFirstChild( "Humanoid" ) |
05 | h.Health = h.Health - 6 |
11 | 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.
01 | local function PlayerTouched(Part) |
02 | local Parent = Part.Parent |
03 | if game.Players:GetPlayerFromCharacter(Parent) then |
04 | for number = 100 , 0 , - 10 do |
05 | Parent.Humanoid.Health = number |
11 | 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.
2 | local h = hit.Parent:findFirstChild( "Humanoid" ) |
4 | h.Health = h.Health - 6 |
9 | script.Parent.Touched:connect(onTouched) |
Hope you learned something from this.
Have a lovely day of coding