GetComponent is null (145969)

script is attached to gameobject.
I am trying to access mybutton’s click event from that script.

void start() {
   var mybutton = GetComponent<Button> ();
   Debug.Log (mybutton);
   mybutton.onClick.AddListener(() => { buttonClick(1); }); 

But it is always null.
Why am i not able to access the button?

I have included using UnityEngine.UI;

2 Answers

2

This means that the gameObject your script is attached to does not have a button component.
In your script, the s in start must be capitalized, so it looks like Start().
The button component must be attached to the same gameObject as your script for it to work.

Sir, This is how it looks. Main Camera Canvas mybutton mygameobject ... Script is attached to mygameobject and i can access the gameobject through this script. But mybutton is not accessible. How do i access it? If it is not possible, If i attach a different script for mybutton, how can i transfer the call from mybutton script to mygameobject script? If the mybutton is clicked, few functions from mygameobject should be called. How can call them?

I have been searching for a very simple solution to practice unity. But no one is ready to help with this simple code. Huge Disappointment! I started to learn from ui elements after seeing a huge community with huge confidence. But i received only disappointment with "I don't know" reply.

Thanks! I understand now additional details :)

var mybutton = GetComponent (); means that you are trying to get the “Button” component of the gameobject on which you have attached this script. You don’t have such component on mygameobject so it is normal that it crashed.

What you want to do is write “public Button MyButton;” in the variables of your class/script (on the top after your class declaration). This will add it as an attribute of your script. Then in the unity editor you can drag and drop your myButton object on the MyButton attribute of your script on mygameobject.