Blueprint: How to switch between indexes with a press of a button?

I’m sorry if this question doesn’t make much sense, I’m fairly new to blueprint, but I’ll try my best to get my question across as clearly as possible.

So, basically, what I did is create a Structure and a component that is attached to the player. In the component Event Graph, I did the following blueprint:

On Event Begin Play, I created a Resize node, with the structure I made as the target array, and an integer variable, let’s call it “Array size”, and made the default value of this variable “10”.

As far as I understand, Resize node takes a variable and creates an index based on whatever desired value. So, in my case, since I input “10” as the default value, now I have an index (of this array of structures) from 0 to 9. I hope I understood right, correct me if I’m wrong.

Now, my question is, I want to create an event where I press 2 keys that will allow me to switch between these indexes. let’s say the buttons are “1” and “2”

Key “2” will move me forwards, so if my current index is 0, and I keep pressing “2” it will move me to 1, 2, 3, 4… so forth. Until I reach 9 and it will take me back to 0 and keep looping that way indefinitely.

Whereas if I press “1”, it will take me backwards.

So, this still happens based on my current index. For instance, if my current index is, let’s say 6, and I press “1” it will take me back to 5, and from there, if I press “2” it will take me back to 6.

How do I convey this in blueprint?

I hope I made sense, and I appreciate your help.

1 Like

Something like

where, NextIndex is

1 Like

That’s exactly what I’m looking for, thank you! :pray:

Perhaps you’d like to explore modulo:

1 Like

Does that work when it’s negative too?.. :thinking:

1 Like

Not starting another forum war over what modulo does to negative values. :rofl:

-5 % 3 = -2 (Python)
-5 % 3 = -2 (Java)
-5 % 3 = 1 (C/C++)
-5 % 3 = 1 (Ruby)

:innocent:

1 Like

No war, just wondering… :disguised_face:

  • Yes, if we -=, we get a wrapping: 0,-1,-2,-3 and back to 0
  • No, it’s useless with array indexing, you’d need to invert it and end up with a wiry mess

If I need to do an array indexing up / down cycle, I generally use a mix of modulo and the thing you did for stepping backwards:

2 Likes

That’s interesting, thank you so much! :grin: :pray:

Thank you so much for providing the link, “cycling array elements” is exactly what I wanted! :pray: