I am not very experienced with C#. I am trying to build circular lists and I have done it like this:
public List<string> items = new List<string> {"one", "two", "three"};
private int index = 0;
void nextItem() {
if (index < items.Count - 1)
index += 1;
else
index = 0;
setItem();
}
void previousItem() {
if (index > 0)
index -= 1;
else
index = items.Count - 1;
setItem();
}
void Update() {
if (Input.GetKeyDown(KeyCode.RightArrow)) nextItem();
else if (Input.GetKeyDown(KeyCode.LeftArrow)) previousItem();
}
But now I am wondering: Am I reinventing the wheel? Does C# already come with a proper data structure for this?
EDIT: In case some context is needed. I have a game menu, where I display a collection of items, and I want that when I press "next" and Im at the last one, to show the first item again.
With utilization of the %
(remainder) operator your code gets quite simple:
void nextItem() {
index++; // increment index
index %= items.Count; // clip index (turns to 0 if index == items.Count)
// as a one-liner:
/* index = (index + 1) % items.Count; */
setItem();
}
void previousItem() {
index--; // decrement index
if(index < 0) {
index = items.Count - 1; // clip index (sadly, % cannot be used here, because it is NOT a modulus operator)
}
// or above code as a one-liner:
/* index = (items.Count+index-1)%items.Count; */ // (credits to Matthew Watson)
setItem();
}
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