- Home /
How to position UI object relative to parent
With the new UI system, is there a way to position a child (via script) to a relative percentage of its parent's dimensions?
E.g., Say I want to position child ⅓ of the way down its parent, which is 150 points in height, I could write: child.anchoredPosition.y = 0.333;
I realize I could grab the parent's size and calculate it myself, but just wondering if there's a built-in way with this new UI system.
Answer by fermmmm · May 12, 2016 at 06:23 AM
You cannot grab the parent size, because the size is relative to the anchors. Your "parent size" will be available as soon as the anchors of the parent are placed joined.
You can move the anchors of the object (anchorMin and anchorMax) these values also moves the object and the value range goes from 0 to 1, so if you place your anchors in the middle of the object in the editor and then in code you move them to (0.5, 0.5) using anchorMin and anchorMax, you will get your object in the center of the parent (for example).
If you can't move the anchors or you find it over complicated, you are going to need some math. Try the "Rect Transform Extended" asset, you can move and scale things around ignoring anchors: https://www.assetstore.unity3d.com/#!/content/41927
Answer by daleth90 · May 12, 2016 at 04:29 AM
[SerializeField]
private RectTransform childPrefab;
[SerializeField]
private Vector2 childAnchor = new Vector2( 0.5f, 0.3f );
private void CreateChild() {
RectTransform theChild = Instantiate( childPrefab );
theChild.SetParent( transform, false );
theChild.anchorMax = childAnchor;
theChild.anchorMin = childAnchor;
}