How do you make a breakable loop in Scratch? I'm using Scratch 2.0 and can't find any good way to make a loop breakable, from inside of the loop itself.
To create a loop like this in Scratch, you would need to use the repeat (number) block. This allows you to repeat a sequence of commands a particular number of times; you set the number of times the loop will repeat at the top of the block. In programming, this type of loop is called a 'count-controlled' loop.
Using Loops in Scratch Loops are great tools to use within code and projects to repeat an action multiple times. In the 'Control' section of block code, there are three types of loops: repeat x number of times, repeat until, and forever.
There are three types of loops in the 'Control' section of block code: repeat x number of times, repeat until, and repeat forever. Each type of loop serves a different purpose, and understanding what they do is essential when writing code.
A “forever” loop, one that runs over and over again until the end of the program, is also called an infinite loop.
There is no perfect way to do it. If you can possibly stand this true fact then feel free to continue.
There are a few different ways you could do it.
repeat until
The first and most simple one follows this:
But this isn't technically part of the script - it's just repeating until some value returns true.
stop this script
)In order to do it inside of the script, you'll need to use a sneaky little trick with custom blocks.
Create a custom block called whatever you want - but probably along the lines of "breakable loop". Inside of it, create this script:
By using stop script
we are breaking out of the script that is currently running - which, according to Scratch, is the custom block.
See the result! (as scratchblocks)
broadcast and wait
You could also use a broadcast-and-wait method, very similar to above:
Though I highly suggest you don't use this method, as if any other sprites have breakable loops you'll need to rename each one, which can be tedious after using a lot of loops in a lot of sprites!
(Note this bug has been fixed in version 442 of the editor and such the following no longer applies.)
Help! My project is lagging a bunch now!
As @foi has noticed, if your code must be run inside of a frame you probably checked run without screen refresh. Unfortunately, due to a bug in the Scratch player, this causes the program to essentially break after the
stop this script
block has been activated. How can you handle this?It follows the same principle you use when you use a run without screen refresh custom block inside of a
forever
loop - the loop doesn't use screen refresh while the inside does, allowing for instant animations whether or not one is using turbo mode.Here's an example - the image is really too long to be embedded, so see it here instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With