Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question about multiple buttons using the same onClick but with different conditions

Discussion in 'Editor & General Support' started by PottyGamer, Oct 1, 2021.

  1. PottyGamer

    PottyGamer

    Joined:
    Sep 23, 2021
    Posts:
    7
    Hello!

    I have a scene with about 30 buttons, which will all perform the same action, but with 2 different parameters. So I want to use the same onClick function, but I'm struggling to figure out how to pass these two parameters for the script to use.

    For example. If the two "parameters" (apologies if that's not the right term) unique to each button would be an 'animal' and 'quantity'. When I click the button, I want the code to adjust the quantity of the animal.

    I figured I could use a unique tag on each button, but that really only gets me 1 of the 2 parameters to pass to the code (unless I split the text of the tag, and I figure there has to be a better way of doing it).

    No code to show yet, but here's a simple example to help you visualize what I'm trying to do....

    Imagine I have 4 buttons named monkey1, monkey10, lion1, lion10

    when I click the button, I want to increment a variable (lets say monkeyQty or lionQty) by 1 or 10 accordingly.

    Hope that helps. And thanks in advance for any guidance!
     
  2. Graunarmin

    Graunarmin

    Joined:
    Oct 31, 2019
    Posts:
    3
    So I think in the Function you call OnClick() (The function you link in the editor to the OnClick() event) you could either take two parameters, a string and an int for example, and then when you set up that function in the editor you can specify the variables for each button directly in the editor. Or - what I would do - take a Button as parameter, then drag and drop each Button into it's own field when you set up the OnClick() Event. In your Code you could then for example get the text Component from the button and do sth. with the string.
     
  3. PottyGamer

    PottyGamer

    Joined:
    Sep 23, 2021
    Posts:
    7
    Thank you. That makes sense. I just can't seem to figure out how to add the variable to the onClick() function. I've seen it before (a field below the function name in the inspector), but I can't remember how I got it to show up before.

    I tried something like:
    Code (CSharp):
    1. public void AnimalButtonTapped(string animalName, int animalQty) {
    2.  
    3.     }
    I hoped that would open 2 fields in the inspector that I could edit. But it didn't seem to work.

    Sorry for my newish question. Still quite new at this.