Find GUI Button and Assign Text

I need to find a GUI Button, currently I do so with GameObject.Find() which results in the problem of treating it like a GameObject, preventing me from referencing the text of the button using the Button.text component. Is there another way to reference the text of a button that would work if the script treats it as a GameObject? Lines 18 and 19 of the following script contain the portion that I’m having trouble with. If I must I can manually go through and rename the buttons, but currently they’re all named “ItemN” where “N” is a number between (inclusive) 1 and 84.

using UnityEngine;
using System.Collections;

public class InventoryScript : MonoBehaviour {

	public object[] inventory;

	public GameObject playerinventory;

	// Use this for initialization
	void Start () {

		inventory = GameObject.FindGameObjectsWithTag ("Tool");
		int i = 1;

		foreach (GameObject item in inventory) {
			if (item.transform.parent == playerinventory.transform) {
				GameObject button = GameObject.Find (("Item" + i).ToString());
				button.text = item.name;
			}
			i = i + 1;
		}
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

I will assume that you are using Unity 4.6 UI system so here’s the solution:

You are finding your GameObjects and you are trying to change the text of the GameObject which is not correct,
Assuming you’re using Unity 4.6 UI system start by importing the UI library:

Add:
using UnityEngine.UI;
at the top of your code.

Now using Buttons usually creates a GameObject that has a Button script with a Child GameObject that has a Text script (the Label).

Easiest approach is to add all your buttons in a “parent” GameObject, and loop through all the children and change the name.

Here’s the code:

using UnityEngine;
using System.Collections;

//Add this to use the new UI library
using UnityEngine.UI;

public class InventoryScript : MonoBehaviour {

    //This is the parent object that includes all the inventory items
	public GameObject playerinventory;
	
	void Start () {
		foreach (Transform item in playerinventory.transform) {
			item.gameObject.transform.FindChild("Text").gameObject.GetComponent<Text>().text = item.gameObject.name;
		}
	}
}

Tested working (Y)