- Home /
Detecting which UI button was pressed within canvas?
Hi!
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);
});
}
$$anonymous$$y guess would be that this.GetComponent() return null. Is this script attached to a button? This might help to prevent that in the future:RequiredComponent
What did you change that it stopped working? Is this Unity 4 or 5?
Hi! The script is attached to the canvas, and the canvas has 10 buttons on it.
I am not sure what I changed, I closed unity and open it up later and this error popped.
Answer by alok-kr-029 · Jun 18, 2015 at 12:24 PM
you can pass the gameobject as a parameter of the function via inspector that you call while the button is clicked .
This is the best mehod that I use to dedect which button is clicked