Search Unity

Bug or user error? Instantiating prefab onto canvas zero's out child object's position?

Discussion in 'UGUI & TextMesh Pro' started by Jesse_Pixelsmith, Aug 24, 2014.

  1. Jesse_Pixelsmith

    Jesse_Pixelsmith

    Joined:
    Nov 22, 2009
    Posts:
    296
    I have a prefab with a a child object positioned below it. When I drag this prefab into a scene it behaves as expected.



    However when I instantiate it all children have their rect transform coordinates set to 0.

    I must be doing something wrong, this seems too basic to be a bug :)
     
    Housei-Yoshida likes this.
  2. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,653
    How are you changing the parenting of the object after you instantiate it?
     
  3. Jesse_Pixelsmith

    Jesse_Pixelsmith

    Joined:
    Nov 22, 2009
    Posts:
    296
    Figured out the issue. Force of habit led me to pass position and rotation parameters on instantiate.

    GameObject icon = Instantiate(Resources.Load("BuildingPlanMaterialIcon"), Vector3.zero, Quaternion.Identity) as GameObject;

    Taking those two extra parameters out fixed it. But I'm still confused as to why instantiating the prefab at Vector3.zero would affect the local position of the "QtyFill" child object of the instantiated prefab.

    Also I'm just parenting to a layout group gameobject that I have defined on my Master UI script.
    icon.transform.parent = selector.MasterUIClass.BuildingPlanMaterialWindow.transform;
     
  4. Tim-C

    Tim-C

    Unity Technologies

    Joined:
    Feb 6, 2010
    Posts:
    2,225
    Use Transform.SetParent() with the second argument set to false, it is the correct way for GUI elements and we are contempleting removing the other option (or at least deprecating it)
     
    Hobsie likes this.
  5. JAKJ

    JAKJ

    Joined:
    Aug 17, 2014
    Posts:
    185
    I found the SetParent function super useful for implementing a tooltip: I used SetParent(...,false) to position the tooltip relative to a child object, and then used SetParent(...,true) to move it into the top level of the canvas so it would be in the same position but drawn above everything else.