I have probably been overthinking it but I am trying to take a list I have and go through the list one by one with a keypress.
For example, I have three strings in a list, and when the player presses L it goes from option 1, to 2. Then 2 to 3. Then 3 to 1. I also need to save this option to a separate string.
Thanks to anyone who can help
Edit:
So I have one script that checks if they key has been pressed
private void Update()
{
if (Input.GetKeyDown(KeyCode.L))
{
gs.ChangeLevel(levelTxt);
}
}
And then on a different script I have the function that will change the option. I know this isn't correct but hopefully you will be able to see what i am trying to do
public List<String> levels;
public string level;
public void ChangeLevel()
{
level = levels.Count[]++;
if(levels.Count > levels.Count)
{
levels.Count[0];
}
}
Edit #2
So I have almost got it with help from the comments. I just need it to increment now (if this is suppose to it will only stay on the first one)
```
public string IncrementLevel()
{
if (levels.Count == 0)
{
levelIndex = 0;
return "";
}
levelIndex = (levelIndex >= levels.Count - 1) ? 0 : levelIndex++;
return levels[levelIndex];
}
And
public void ChangeLevel(Text level)
{
level.text = levels[levelIndex].ToString();
Debug.Log("It is now set to " + levels[levelIndex]);
}
Edit #3
Hey again guys, so the code shared in the comments helped but now I need to take it and decrease it with a different button. Any help would be appreciated.
I am not sure if we are on the same wavelength, however, if you just want to iterate a list then you need a pointer. You can create a function to increment the pointer and pop the value all in one.
private List<string> levels = new List<string>();
private int levelIndex = -1;
public string IncrementLevel()
{
levelIndex = (levels.Count == 0) ? -1 : (levelIndex >= levels.Count - 1) ? 0 : levelIndex + 1;
return (levelIndex == -1) ? "" : levels[levelIndex];
}
public string DecrementLevel()
{
levelIndex = (levels.Count == 0) ? -1 (levelIndex <= 0) ? levels.Count - 1 levelIndex - 1;
return (levelIndex == -1) ? "" : levels[levelIndex];
}
and
private void Update()
{
if (Input.GetKeyDown(KeyCode.L))
{
gs.ChangeLevel(IncrementLevel());
}
}
Try this:
// not tested for compilation, I used 0 as the start
// since that's the index of the first item in a list
int index = 0;
if (Input.GetKey("L"))
{
index++;
if (index > 2)
{
index = 0;
}
// the item you want is yourList[index],
// do whatever you want with it, just make sure
// it's used after the if index > 2 statement;
}