For Loops!
What is a for loop?
In Lua, you would write a for loop like this,
for i = 1,10 do
print(i)
end
The output would look like this,
1
2
3
4
5
6
7
8
9
10
i is a variable that will get added by 1 each time. Normally you would add a number to i each time, but Lua will automatically do this for you. If you wanted to make i count down, you would subtract by 1 each time, like so,
for i = 10,1,-1 do
print(i)
end
Counts down from 10
Your question
To make your code shorter, just do a for loop, like so,
local partParent = script.Parent
function onTouch(part)
local human = part.Parent:FindFirstChild("Humanoid")
if (human ~= nil) then
partParent.Anchored = false
wait(5)
for i = 1, 10 do
partParent.Transparency = i/10
wait(.01)
end
game.Workspace.fallingPart:Destroy()
end
end
partParent.Touched:connect(onTouch)
Optional changes
You could also combine your event and function like this,
local partParent = script.Parent
partParent.Touched:connect(function(part)
local human = part.Parent:FindFirstChild("Humanoid")
if (human ~= nil) then
partParent.Anchored = false
wait(5)
for i = 1, 10 do
partParent.Transparency = i/10
wait(.01)
end
game.Workspace.fallingPart:Destroy()
end
end)
You could even get rid of the variable as it's only making the script larger. This does nothing but shorten the script though,
script.Parent.Touched:connect(function(part)
local human = part.Parent:FindFirstChild("Humanoid")
if (human ~= nil) then
script.Parent.Anchored = false
wait(5)
for i = 1, 10 do
script.Parent.Transparency = i/10
wait(.01)
end
game.Workspace.fallingPart:Destroy()
end
end)
Last optional change would be removing the human variable because you're not using it.
script.Parent.Touched:connect(function(part)
if part.Parent:FindFirstChild("Humanoid") then
script.Parent.Anchored = false
wait(5)
for i = 1, 10 do
script.Parent.Transparency = i/10
wait(.01)
end
game.Workspace.fallingPart:Destroy()
end
end)
Side note,
Your script will now be shorter, but this does almost nothing to affect it's efficiency. There's really not much you can do that would change the efficiency of your script. If I were you, I wouldn't worry about efficiency so much. You should however work on making your scripts smaller. Less code is easier to handle.
Hope I helped!
Good Luck!
2 comments
Oh wow, this is cool! I just rewrote a script from the Hour of Code tutrial to do this. Thanks!
np