PcoWSkbVqDnWTu_dm2ix
Introduction to Coding
Part 3 - Loops
Introduction to Coding
Part 3 - Loops

Looping Code

The platform should be constantly disappearing and reappearing, with a few seconds between each change. It’s impossible to write an infinite number of function calls — fortunately, with a while loop, you don’t have to.

A while loop runs the code inside it for as long as the statement after while remains true. This particular loop needs to run forever, so the statement should just be true.

  • Create a while true loop at the end of your script.
local platform = script.Parent

local function disappear()
    platform.CanCollide = false
    platform.Transparency = 1
end

local function appear()
    platform.CanCollide = true
    platform.Transparency = 0
end

while true do

end

Toggling the Platform

In the while loop, you’ll need to write code to wait a few seconds between the platform disappearing and reappearing.

The built-in function wait can be used for this. In the parentheses the number of seconds to wait is needed: for example wait(3).

Three seconds is a sensible starting point for the length of time between each platform state.

  1. In the while loop, call the wait function with 3 in the parentheses.

  2. Call the disappear function.

  3. Call the wait function again with 3 in the parentheses.

  4. Call the appear function.

    local function appear()
    	platform.CanCollide = true
    	platform.Transparency = 0
    end
    
    while true do
    	wait(3)
    	disappear()
    	wait(3)
    	appear()
    end

The code for the platform is now complete! Test your code now and you should find that the platform disappears after three seconds and reappears three seconds later in a loop.

You could duplicate this platform to cover a wider gap, but you’ll have to change the wait times in each script, otherwise the platforms will all disappear at the same time and players will never be able to cross.

local platform = script.Parent
 
local function disappear()
    platform.CanCollide = false
    platform.Transparency = 1
end
 
local function appear()
    platform.CanCollide = true
    platform.Transparency = 0
end

while true do
	wait(3)
	disappear()
	wait(3)
	appear()
end


Previous Page Functions