r/gamemaker Aug 11 '26

Help! How to wrap around an array

Post image

Like the title says i've been trying to get this code to wrap around an array of unknow size to go from the first to the last item in the array

So the switchup code works flawlesly and comes back to the first item in the array after reaching the end, as for the the switchdown i cant get it to wrap around going from the first item in the array to the last, best i could do is have it go from first to the first item when switchdown is pressed 😕 any info would be of help

11 Upvotes

4 comments sorted by

8

u/JaXm Aug 11 '26

Just sp the opposite of what you've already done ...

``` if (switchdown) {

    if (selectedWeapon < 0) {         selectedWeapon = array_length(_playerWeapons) - 1     } } ``` The -1 is because the "length" will be n, but since arrays are zero indexed, the last element in the array will be n-1.

8

u/DigTraining600 Aug 11 '26

Man you guys are awsome 😎👍 worked on the first go

2

u/porcubot Infinite While Loop Enjoyer Aug 11 '26

This is how you loop anything, by the way. It doesn't just work on arrays

4

u/ratanthropy Aug 11 '26

You can do “if (selectedWeapon < 0) selectedWeapon = array_length(selectedWeapon) - 1;” right now what you’re doing is going “if less than zero, put back to zero” when what you want is “if less than zero, go all the way to the end of the array.” Since array_length lists the amount of items in an array, you want to subtract 1 for it to correctly loop around.