- Home /
Can´t instantiate objects in list correctly
The method is called when my document gameobject is picked and added to, the list i have (documents) When I have only 1 item in my list, the I can grab the documents info (title, etc), and make them show them the info in my UI when clicked, not necessary to post that method.
BUT, when I have 2 or more items in my list, I cannot access any item in the document list anymore, I believe its the int (documentIDToinstance), what this does is instantiating the correct ".document" info to the new UI element, so it shows like the actual document
public void PickedDocumentUp()
{
GameObject newbuttonToInst = Instantiate(FilePrefab);
newbuttonToInst.name = documents[documentIDToInstance].documentTitle;
newbuttonToInst.transform.parent = gameObject.transform; //Sets where to instantiate the newButton
newbuttonToInst.transform.localScale = new Vector3(1f, 1f, 1f); //Sets the correct scale of the newButton
newbuttonToInst.GetComponent<Button>().onClick.AddListener(() => { ReadClickedDocument(); }); //Set the function to read the document
Component[] components;
components = GetComponentsInChildren<Text>();
components[0].GetComponent<Text>().text = documents[documentIDToInstance].documentTPreview; //Take and set the taken document title
components[1].GetComponent<Text>().text = documents[documentIDToInstance].documentTitle; //Take and set the taken document body
components[2].GetComponent<Text>().text = documents[documentIDToInstance].documentBody; //Set the document preview
//_documentTPreview.text = documents[documentIDToInstance].documentTPreview;
documentIDToInstance = documents.Count;
}
I hope I explained myself well. Hope anybody can guide me or show me some solutions. I believe the error is when instantiating the prefabs. Thanks!
Answer by Inok · Oct 06, 2015 at 11:23 PM
You know that first index in array start at 0 (zero), so i not undestand why you assign here "documentIDToInstance = documents.Count;" Maybe you need "documentIDToInstance = documents.Count - 1;" Sorry if i wrong.
The error was in here:
Component[] components;
components = GetComponentsInChildren<Text>();
The fix was only adding this:
Component[] components;
components = newButtonToInst.GetComponentsInChildren<Text>();
The documents.Count will be default Zero. so it will start counting by zero :) If there's nothing in the documents List, it will be zero. But thanks for your answer! $$anonymous$$aybe it'll be useful for someone :)