# How do I refer to the object that called a function?

I have a large number of buttons instantiated from a prefab using a loop, as follows:

public void LayoutButtons() {

GameObject newCanvas = Instantiate (canvas) as GameObject;

for (int i = 0; i < 10; i++) {
GameObject newButton = Instantiate(button, new Vector2((i * 100.0F)-500, -100), Quaternion.identity) as GameObject;
newButton.transform.SetParent (newCanvas.transform, false);
}

}


I would like the OnClick function to output the clicked button's text. However, I don't know how to reference the clicked button. I tried doing Debug.Log(this.GetComponent<Text>().text) but I get a NullReferenceException: Object reference not set to an instance of an object.

I'm not positive I'm using this correctly but I have limited connectivity at the moment and can't think of what else I'm doing wrong.

• What Object is your script with the OnClick function attached to? – Fuzzy Logic Aug 3 '15 at 5:15
• You shouldn't put 'this' before GetComponent() – Vadim Tatarnikov Aug 3 '15 at 7:02
• @Fuzzy Logic, it's on the button prefab. I've tested that it registers clicks and it does. – Matt Aug 3 '15 at 10:13
• There's nothing wrong with using 'this' in the way that has been done although it is redundant. Just try to be consistent or only use 'this' to disambiguate. – Fuzzy Logic Aug 3 '15 at 13:22

You need to find references to Button and Text components on your instantiated objects, not on your controller object. Depending on your prefab hierarchy you can use GetComponent or GetComponentInChildren.

public void LayoutButtons()
{
GameObject newCanvas = Instantiate(canvas) as GameObject;

for (int i = 0; i < 10; i++)
{
GameObject go = Instantiate(buttonPrefab, new Vector2((i * 100.0f) - 500, -100), Quaternion.identity) as GameObject;
go.transform.SetParent(newCanvas.transform, false);
var button = go.GetComponent<Button>();
var text = go.GetComponent<Text>();
}
}


If your OnClick handler is in a script attached to your button prefab then you can do something like the following:

public void OnClick() {
UnityEngine.UI.Text textComponent = GetComponentInChildren<UnityEngine.UI.Text>();
Debug.Log(textComponent.text);
}


Basically, you are on the right track but you need to search for the component in the children of the Button object, not the button itself. Key problem is GetComponent() instead of GetComponentInChildren().

The NullReference error is because the Text component was not found attached to the Button, so it returns null.