0

Spent the last 1-2 hours looking for the answer and haven't quite got it, I'm hoping it's something simple.

I have created an array of a custom class with just a small number of values like so (where Person is a Class):

Person person[] = new Person[2]; 

(Note I'll be replacing the 2 with a variable like numberOfPeople)

I need to create a method that I can call when needed (on a button press for example) that will move from the current person to the next in the array (going back to the start when it reaches the end).

In other words: On button press - move from player0 to player1.

I've been looking at how to use For, ForEach, If etc to do this but can't work it out.


SOLVED VIA Vincent Ugenti's ANSWER. In case other noobs come across this to solve their problem, had a few subsequent noob issues where I was trying to define the number of values in the array with a variable which wasn't given a value until after the array was made (causing instant crashing) and then I forgot doing nothing more with the code than this won't run each objects Constructor which needs to be done separately.

2 Answers 2

1
  • Create a variable such as "currentPerson"
  • In your event handler (whenever you want to advance to the next person), currentPerson = (currentPerson + 1) % numberOfPeople
  • The current person is then always person[currentPerson]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, got it! In case others come looking for the same thing: I had a few subsequent noob issues where I was trying to define the number of values in the array with a variable which wasn't given a value until after the array was made (causing instant crashing) and then I forgot doing nothing more with the code than this won't run each objects Constructor which needs to be done separately.
0

Keeping track of the current index and hooking a button event is what you want to do.

On button press check your variable, increment it by 1 and check if that value is not greater than the length of the array.

If its not greater than the array length you can grab the element, else reset the count to 0 and do what you need to do.

If youre only doing this on button press (event handler) you shouldnt need to use any loops.

1 Comment

Thanks, I managed to get it with Vincents answer already though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.