Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Found a weird behaviour while anchoring gameobjects from a script

Discussion in 'UGUI & TextMesh Pro' started by Ilingis, Sep 13, 2016.

  1. Ilingis

    Ilingis

    Joined:
    Dec 13, 2012
    Posts:
    63
    Why is it that when I anchor a gameobject to the left side, it works only when I parent the GO to the panel AFTER I set an anchorposition of the Object and when I want to anchor a gameobject to the right side of the panel I need to parent it to the panel BEFORE I set the anchorposition? Is it supposed to work like this? Was this behaviour intended?
     
    Last edited: Sep 13, 2016
  2. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    I would be interested in seeing your code and what values you set for the RectTransform. AnchoredPosition, offsetMin and offsetMax are all very much relative to where you set the Pivot as well as the Anchors themselves.

    On an empty Scene Create a UI Panel, then make a Button the Child of that Panel. Attach this script to the button and try setting the anchors, pivots and move the button around. You will see how the various fields change based on where you set the anchors, and pivots.

    Code (CSharp):
    1.  void Awake()
    2.     {
    3.         RectTransform rt = GetComponent<RectTransform>();
    4.         Debug.Log("Anchored position: " + rt.anchoredPosition);
    5.         Debug.Log("Pivot: " + rt.pivot);
    6.         Debug.Log("OffsetMin" + rt.offsetMin);
    7.         Debug.Log("OffsetMax" + rt.offsetMax);
    8.     }
    I think the trouble your having is when you parent an object after you set the variables, it does some conversions to make the object stay relative to where it is now. Possibly those conversions do nothing when it starts anchored to one side or the other. Best to understand what all the variables are exactly doing, and parent it first no matter what then set your anchor points and pivots relative to the parent.

    Also if you state where you you would want a child inside a parent, and how you want it to stretch if the parent stretches, I can give you the code you need to attach to the parent correctly if you need help with that.