Detecting which UI button was pressed within canvas?

4k Views Asked by At

I have like 10 buttons on my UI and I gotta check which one was touched. I was using the following logic and it was working fine, but now I am getting this error for some reason:

 NullReferenceException: Object reference not set to an instance of an object
 DetectButton.Start () (at Assets/Scripts/DetectButton.cs:14)

Any ideas what could be going on? Here is my code (attached to the canvas), and I am using Unity version 5.1.0f3. If you need any other info I will gladly provide, thanks in advance

void Start()
 {
     this.GetComponent<Button>().onClick.AddListener(() => 

                                                     { 

         if (this.name == "btnJogadores2")
         {
             print ("2 jogadores");
             jogadores = 2;
         }
         //QuantidadeJogadores(this.name);
         //QuantidadePartidas(this.name);
     }); 
 }
2

There are 2 best solutions below

0
On BEST ANSWER

You don't have to all this the way you are doing.

An Easier and good practice would be to create 10 separate GameObjects for each button inside your canvas. and then create a single script with 10 separate functions for all those buttons in it. Attach that script to you canvas. and then on the button GameObject select the script on the desired function. Sample below

void Start() { }
void Update() { }

public void button1()
{
    Debug.Log("Button3");
}

public void button2()
{
    Debug.Log("Button1");
}

public void button3()
{
    Debug.Log("Button3");
}

NOTE: button1, button2 and button3 are the functions for 3 separate buttons

Then inside your unity Inspector: _See this sample image_

  1. Select your script with you button functions.
  2. Assign you desired method to you button.

After this run your scene and your button will call the assigned methods properly.

1
On

Code is not tested, but it should get you started to get all the Buttons.

void Start() {
        var buttons = this.GetComponents<Button> ();
        foreach(var button in buttons) {
            button.onClick.AddListener(() = > {
                if (this.name == "btnJogadores2") {
                    print("2 jogadores");
                    jogadores = 2;
                }
                //QuantidadeJogadores(this.name);
                //QuantidadePartidas(this.name);
            });
        }
    }

Actually it will be hard to distinguish between the buttons. The more practical aproach would be to make 10 GameObjects (Child of the Canvas) and attach your Script to everyone of them.