-3
\$\begingroup\$

This question already has an answer here:

how do I get a function from another script and insert it into a button, I did this is giving this error

"Object reference not set to an instance of an object"

public Button Mybutton;

    void Indice(){
        if (index <= 0)
    {
        index = 0;
    }

    if (index >= 2)
    {
        index = 2;
    }

        if (index == 0)
    {
        Mybutton.GetComponent<Button>().GetComponent<MyScript>().MyFunction();
    }
    else if (index == 1)
    {
        Mybutton.GetComponent<Button>().GetComponent<MyScript>().MyFunction2();
    }
    else if (index == 2)
    {
        Mybutton.GetComponent<Button>().GetComponent<MyScript>().MyFunction3();
    }
\$\endgroup\$

marked as duplicate by msell, DMGregory unity May 15 at 12:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • \$\begingroup\$ MyButton is already of type Button, so Mybutton.GetComponent<Button>() is redundant. But if ultimately what you want is a MyScript, why not just make your variable public MyScript myScriptInstance; instead? \$\endgroup\$ – DMGregory May 15 at 12:56
  • \$\begingroup\$ while to this I know, the business is to get this void and pass it to a button, is that I'm still learning \$\endgroup\$ – Rangel May 15 at 13:39
0
\$\begingroup\$

There are some errors:

Mybutton.GetComponent<Button>().GetComponent<MyScript>().MyFunction();
  1. MyButton is correctly referenced ?
  2. If Yes, just use: MyButton.GetComponent().MyFunction();

To get MyButton reference use:

GameObject MyButton = GameObject.Find("MyButton");
\$\endgroup\$
  • \$\begingroup\$ continue the error, I added public Scripty MyScript; public Button MyButton; MyButton.GetComponent<MyScript>().MyFunction(); \$\endgroup\$ – Rangel May 15 at 17:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.