Help with button Text and error
Hi Everyone,
This is probably extremely simple and I just can't see it... but...
I just don't seem to be able to change a button text with a script.
This is my script
public void OpenInv()
{
isOpen = true;
invWindow.SetActive (true);
invScroll.SetActive (true);
//Create a button foreach item in stock
foreach (ItemStock stocked in stock) {
Debug.Log (stocked.itemName + stocked.itemAmount);
var newItemICon = Instantiate (itemIcon, this.transform.position, Quaternion.Euler(new Vector3(0,0,0f))) as GameObject;
newItemICon.transform.parent = itemContainer.transform;
Text newIconText = newItemICon.GetComponent<Text>();
newIconText.text = stocked.itemName;
}
}
It all runs smooth until the last two lines. There Unity gives me a NullReferenceException.
stock is a simple class it has two variables string itemName and Int itemAmount.
What I want is for each button created from a list of objects to name the button as the ItemName...
Thanks in advance.
Comment
Best Answer
Answer by Merrick20 · Mar 02, 2017 at 04:04 PM
I knew it... after a good night rest I solved it myself... I don't know if anyone will find it usefull but this is what I corrected...
newItemICon.transform.GetChild(0).GetComponent<Text>().text = stocked.itemName;
//Text newIconText = newItemICon.GetComponent<Text>();
//newIconText.text = stocked.itemName;
I was referencing the wrong object...