- Home /
Help making multiple buttons do a specific set of actions in any order pressed
Hello,
I have 9 buttons with access to the same script that are all on the scene at once. I want to make pressing the buttons do a predetermined set of actions in the script in any order pressed. For example, if I have an int, no matter which of the 9 buttons I press, pressing a button will add 1 to the int, then pressing another button will add 2, and the third could subtract 3 and so on. The last button pressed will always display the int and display a new button to reset the whole thing.
Answer by lvskiprof · Apr 20, 2021 at 07:59 PM
Hard to picture what your buttons look like from the description, but if what you are asking is how to identify the different buttons you might try assigning a unique tag to each one. The tag will let you determine what action to take.
The buttons are just the default unity buttons sorted in a 3x3 square, labelled button 1-9. I have lines of code such as "Debug.Log("first button pressed")", "Debug.Log("second button pressed")" and so on.
Whether I press button 1, button 4 or any other button first, I want whichever button I press first to always do the Debug.Log("first button pressed") code. Then the second button (which can be any of the other 8 buttons) upon being pressed would do the Debug.Log("second button pressed") code.
The tag wouldn't work because it means that the button I press will do the same command no matter what. Each button would be able to do all 9 lines of code, and would only do the line based on what order it was pressed in.
Now it makes sense. What you need is a state machine and each button press moves you into the next state. In your case that could be a simple counter that starts at 0 and each button press increments the state value.
You then perform the function you want based on the new state value.
I totally forgot about state machines! Embarrassing. I'll make a simple counter state as you recommended. Thank you for the help!