Search Unity

SetParent, SetAsLastSibling changes UI element position?

Discussion in 'Scripting' started by leegod, Jun 7, 2019.

  1. leegod

    leegod

    Joined:
    May 5, 2010
    Posts:
    2,476
    I made some icon UI Image (Img) as child of some ScrollView's children element (Item).

    And make (Img)'s transform.localPosition = new Vector3(Posx, 0, 0);

    At test, (Img)'s y position set well as 0 and looks side by side with (Item).

    But after then,

    I set like

    Code (CSharp):
    1.  
    2. transform.SetParent(GetComponentInParent<Canvas>().transform);
    3. transform.SetAsLastSibling();
    4.  
    Then, (Img)'s y position become different (this is ok) and looks different with (Item) <- This is problem.

    I don't care what (Img)'s y position's number is, but I want (Img) looks side by side with (Item).

    And I did SetParent to topmost Canvas is because rendering order problem. If (Img) is child of (Item), (Img) is hidden by scrollview's border.

    Why moving transform to More topmost UI make its Y position different?
    And how to fix this and achieve my goal?
    Thanks.
     
  2. Neriad

    Neriad

    Joined:
    Feb 12, 2016
    Posts:
    125
    I'm pretty sure you should be using RectTransform and not Transform. It could be solving your issue, worth a try.
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    I'll be honest, I had difficulty understanding what your issue was. But I have found when changing parents with UI components, sometimes you get different behaviors and have to reset position or scale. There are different factors that effect UI components when you move them about.

    The setsibling calls will move them in the order, so if you have a layout group that will change it's position.

    Recttransform should not required to be used for this.
     
  4. leegod

    leegod

    Joined:
    May 5, 2010
    Posts:
    2,476
    you mean, rt = Getcomponent<Recttransform>(); var pos = Vector3(0, 333, 0); rt.position = pos;

    ?