- Home /
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 () {
}
}
Answer by _joe_ · Mar 27, 2015 at 08:47 PM
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)
Your answer
Follow this Question
Related Questions
Force Unity UI element to refresh/update? 4 Answers
How do I set a GUI button's text using a string from another script? 0 Answers
I need to resize my text to button to be visible using Unity 4.6 UI 2 Answers
[4.6 - UI] Change text on button click via script 1 Answer
Having trouble getting text to show up. 0 Answers