- Home /
Button only works once
Hello! I've made a function that makes to read a "document", getting the child objects from where the button is, and putting those texts to show. But when I click the document it shows well, but only ONCE!
For example, if I have 2 documents in my inventory, I only can read the first one I click, and when I click another document, it still shows the info about the first one I clicked.
Here's my code that reads documents:
public void ReadClickedDocument()
{
Component[] components;
components = GetComponentsInChildren<Text>();
//The child #0 of the prefab will contain the title of the document, the next one the body.. etc.
_documentTitle.text = components[1].GetComponent<Text>().text.ToString();
_documentBody.text = components[2].GetComponent<Text>().text.ToString();
}
And this is the code that adds the function to the instantiated button:
newbuttonToInst.GetComponent<Button>().onClick.AddListener(() => { ReadClickedDocument(); }); //Set the function to read the document
I think that's because the scope of ReadClickedDocument(). How about try to add debug log of "the name of game object" in this function to test which object you are actually access?
Nice, I will try that.
It's getting always the parent's name. So that might be the problem. Any solution?
Answer by NDark · Oct 08, 2015 at 02:58 PM
I may try to implement ReadClickedDocument() to a new script binding to button object. And override OnClick() to call this function as well. To achieve your goal.
I didn't use AddListener() before though.
Hope that helps.