Skip to main content

On Sale: GamesAssetsToolsTabletopComics
Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
TagsGame Engines
(1 edit) (+3)

Just to flesh out the implied details of Millie's example, I have an experimental setup with four audio clips named "sound1" through "sound4" (I used Decker to record myself saying the numbers one through 4 to make it clear), a field named "loopcounter", a button for starting the loop with a script like this:

on click do
 loopcounter.text:0
 play["sound1" "loop"]
end

and a button for stopping it like this:

on click do
 play[0 "loop"]
end

That leaves us with the loop[] event handler, which for this setup ought to be defined on the card. If you wanted the music to keep playing across many cards, defining a handler on the deck-level script could also work, but it would then be important to specify the path to the loopcounter field as e.g. "deck.cards.thatCard.widgets.loopcounter" instead of just "loopcounter".

We can simplify Millie's example in a few ways. Firstly, by indexing from 0 instead of 1, we can use the modulus operator (%) to wrap the incremented value of loopcounter between 0 and the length of the list of audio clip names, avoid the need for a "dummy" element at the beginning of the list, and save an "if" statement. We can also coerce a string like "3" to the number 3 by adding 0 to it (or any equivalent arithmetic identity operation) instead of parsing it:

music1:("sound1","sound2","sound3","sound4","sound3","sound3","sound1","sound2")
on loop do
 loopcounter.text:(count music1)%1+loopcounter.text
 music1[0+loopcounter.text]
end

We could make the script more concise still by defining the list of pattern names as a single string that we split on pipes (|) and stashing the loop index in a temporary variable so we don't have to refer to "loopcounter.text" three times or turn the string-ified index back into a number:

on loop do
 m:"|" split "sound1|sound2|sound3|sound4|sound3|sound3|sound1|sound2"
 loopcounter.text:i:(count m)%1+loopcounter.text
 m[i]
end

Since there's a very simple pattern to the names of audio clips we want to play, we could be even more concise by only building a list of the part that varies- the number at the end of the string- and formatting that at the end of the function:

on loop do
 m:1,2,3,4,3,3,1,2
 loopcounter.text:i:(count m)%1+loopcounter.text
 "sound%i" format m[i]
end

Of course, the most important thing is always to use the approach that makes sense to you! Longer code isn't necessarily worse if you find it clearer or easier to modify.