How would I select GameObjects from an array one by one?
So basically, I have a song selection menu in my game, I am using two buttons as arrows, one on the left and one on the right, obviously, the left button would go - in the array and the right arrow would go + in the array, but nooby me, can't achieve this, I can tell its a super simple process, but what I have just goes from 0 to 14 instead of going from 0,1,2,3... etc. (array of 15 items). The "Song Ref" is the selection of the song which gives the output.
public Button leftBtn;
public Button rightBtn;
[Space]
[Header("Array Ref")]
public GameObject songRef;
[Space]
[Header("Song Game Objects")]
public GameObject[] array;
public int selection;
private bool leftButtonIsPressed;
private bool rightButtonIsPressed;
void Start()
{
selection = 0;
}
void RightButtonPressed()
{
if (selection < array.Length - 1) //because size starts at 1, arrays at 0
{
selection++;
}
}
void LeftButtonPressed()
{
if (selection > 0)
{
selection--;
}
}
void Update ()
{
rightBtn.onClick.AddListener(RightButtonPressed);
leftBtn.onClick.AddListener(LeftButtonPressed);
songRef = array[selection];
//change song using refrence
}
Answer by DreadKyller · Dec 22, 2017 at 06:41 AM
From what I can see of your problem, it seems you're adding multiple of the same listener to the button press events. Every frame you're adding another listener, so by frame 13+ pressing a button calls the function 13+ times, thus giving you your issue. Set the event handlers in the Start() method instead of the Update() method, as Start only gets ran once it should only register it once.
Oh my god thank you so much, I'm so stupid for not seeing this.
I'm guessing that means it worked? I've never tried to add the same handler twice so for all I knew Unity ensured no duplicates, this was just the only thing I could think of. And don't call yourself stupid :)