Unity engine: Which component called a running script?

Viewed 96

So, I am trying to build a menu's animations. I want all buttons but the pressed one shunted aside. But since writing a separate script for each button is less than elegant (and in case of dynamic buttons, impractical), I need to think of something else.

So, I want to make a script that will be hooked on several buttons. When any of them is pressed, the script is called, identifies which button called it, and excludes it from having its shunting animation used. For a pseudo-code description:

for (each button){
 if (pressed_button != this_button){
  run this_button's animation
 }
}

But there's a problem: I can't for the life of me figure out how to identify the pressed button! Any tips?

1 Answers

You can add an OnClick event to your button which can call any public function in the script you point it to. You can also pass a single parameter to the function which can be a reference to the button, an int, a string, etc. With this, you could have a single function with a switch statement that handles the button presses based on what you pass it.

enter image description here

Keep in mind, when you add an event to the button component you will need to drag in a GameObject from your scene with the script attached to it in order to access its public functions. You cannot just drag the script itself directly into the OnClick event.

Related