Search code examples
c#unity-game-enginenullreferenceexceptiongameobject

Unity - C# - attach GameObject to public Button CommunicationButton;


I cannot solve this problem, I hope someone knows how to do this.

What I have

A button and a text field on a canvas, see image:

enter image description here

I have a script called HumanInstructions, that initializes like this:

public Text CommunicationMessage;
public Button CommunicationButton;

Right now I can assign the corresponding GameObject in the inspector, by choosing the button/textfield in a dropdown menu.

What I want, is choosing the GameObject through script. The textfield is called CrazyMsg and the button is called CommunicationButton. So I want something like this:

public override void OnAwake ()
{
    CommunicationMessage = GameObject.find("CrazyMsg");
    CommunicationButton = GameObject.find("CommunicationButton");
}

It doesn't work. Help!


Solution

  • It is GameObject.Find not GameObject.find. You also need to get Component after finding the GameObject.

    public Text CommunicationMessage;
    public Button CommunicationButton;
    
    void Start()
    {
        CommunicationMessage = GameObject.Find("CrazyMsg").GetComponent<Text>();
        CommunicationButton = GameObject.Find("CommunicationButton").GetComponent<Button>();
    
        //Register Button Click
         CommunicationButton.onClick.AddListener(() => buttonClickCallBack());
    }
    
    //Will be called when CommunicationButton Button is clicked!
    void buttonClickCallBack()
    {
       CommunicationMessage.text = ....
    }
    

    You can also regsiter Button with CommunicationButton.onClick.AddListener(delegate { buttonClickCallBack(); }); or CommunicationButton.onClick.AddListener(buttonClickCallBack);