Search Unity

  1. New Unity Live Help updates. Check them out here!

    Dismiss Notice

Unity UI I'm having a problem creating UI elements dynamically.

Discussion in 'UGUI & TextMesh Pro' started by Canorange, Mar 25, 2020.

  1. Canorange


    Feb 20, 2020
    I'm trying to make an inventory system: a list of items is stored in an xml file, on game start the list is loaded up by an object and then the name and the amount of each item should be displayed in rows in the UI, a row of text (TextMeshPro) for each item. I'm having a problem with this last bit. Since I'm trying to create dinamically this UI text I created a prefab for the row, i set the RectTransform parameters so that connecting a new row as child to the previous they pile up orderly in the UI.These are the settings:
    It seems to work if I drag and drop my prefab to the hierarchy, but I don't get the same effect when instantiating from script, the text is positioned in a wrong place.This is the code:
    Code (CSharp):
    1.     public void Start()
    2.     {
    3.         foreach(ItemWithAmount item in invMan.itemIterator())
    4.         {
    6.             GUIinventoryLine inst = Instantiate<GUIinventoryLine>(lineBlueprint);
    7.             inst.itemName.text = item.itemName;
    8.             inst.amount.text = "x" + item.amount.ToString();
    9.             inst.transform.SetParent(attachTo);
    10.             attachTo = inst.transform;        
    11.         }
    12.     }
    I actually know why this is happening: when instantiating, since the text isn't child of a canvas the RectTransform parameters are interpreted as world coordinates and the text is therefore spawned in position (0,-25,0), when I then setParent the position is recalculated as relative to the new parent so the text stays where it is.
    Is there a way to make setParent interpret the parameters as local? If not, how can I reposition my text manually under the parent (keeping in consideration that for UI the pivot point of the parent doesn't give me any meaningful information)?
  2. Hosnkobf


    Aug 23, 2016
    Just pass the parent as second parameter in the instantiate method.
  3. Canorange


    Feb 20, 2020
    Ohh, it was that easy. Thanks.