How to set the new Unity UI Rect Transform Anchor Presets via c# script ?
Asked Answered
F

9

0

Hi , how can we set the anchor prest to something like … Top Stretch, as shown in the picture ?

50253-rtap.jpg

i don’t the the default values

Farsighted answered 6/6, 2023 at 3:19 Comment(0)
M
0

You control the anchor point with these values:

alt text

Using code, you can control the anchors with:

All of them are Vector2.

public RectTransform panelRectTransform;

// Something like this.
void Start()
{
   panelRectTransform.anchorMin = new Vector2(1, 0);
   panelRectTransform.anchorMax = new Vector2(0, 1);
   panelRectTransform.pivot = new Vector2(0.5f, 0.5f);
}

Furthermore, the anchor points and these variable are used the most often so in case you aren’t sure what they are:

anchoredPosition controls the positions X and Y positions of the GUI based on the anchor points.
sizeDelta controls the width and height of the GUI.

Marris answered 6/6, 2023 at 2:41 Comment(1)

great , thanks . I totally understand now

Farsighted
S
0
Spurry answered 6/6, 2023 at 2:30 Comment(0)
I
0

public void SetAndStretchToParentSize(RectTransform _mRect, RectTransform _parent)
{
_mRect.anchoredPosition = _parent.position;
_mRect.anchorMin = new Vector2(1, 0);
_mRect.anchorMax = new Vector2(0, 1);
_mRect.pivot = new Vector2(0.5f, 0.5f);
_mRect.sizeDelta = _parent.rect.size;
_mRect.transform.SetParent(_parent);
}

In case if anyone wants to extend the RecTransform class:

 public static void SetAndStretchToParentSize(this RectTransform _mRect, RectTransform _parent)
    {
        _mRect.anchoredPosition = _parent.position;
        _mRect.anchorMin = new Vector2(1, 0);
        _mRect.anchorMax = new Vector2(0, 1);
        _mRect.pivot = new Vector2(0.5f, 0.5f);
        _mRect.sizeDelta = _parent.rect.size;
        _mRect.transform.SetParent(_parent);
    }
Itol answered 6/6, 2023 at 2:41 Comment(0)
F
0

Try this

   public Vector2 UIGetElementDimension (GameObject mGameObject) {

        Vector2 Res = -Vector2.one;
        RectTransform RectTransform = mGameObject.GetComponent<RectTransform>();
        if (RectTransform != null) {
            Res = RectTransform.sizeDelta;          // Read GameObject Dimensions                                                     
        }
        return Res;
        
    }

    public void UIMaximizeElement(GameObject mGameObject, GameObject Parent = null, float Left = 0, float Right = 0, float Top = 0, float Bottom = 0) {

        RectTransform RectTransform = mGameObject.GetComponent<RectTransform>();                    // Get Rect Transform Component from element

        if (RectTransform != null) {

            Vector2 ParentSize = -Vector2.one;
            if (mGameObject.transform.parent != null)                                               // Get Size of Parent
                ParentSize = UIGetElementDimension(mGameObject.transform.parent.gameObject);        

            else if (Parent != null)
                ParentSize = UIGetElementDimension(Parent);

            RectTransform.anchorMin = new Vector2(0, 0);                                            // Set Location respect to Axes, same thing then doit manually in Anchor Min and Max in inspector of Rect Transform
            RectTransform.anchorMax = new Vector2(1, 1);                                             
            
            RectTransform.pivot = new Vector2(0.5f, 0.5f);                                          // Pivot in the Middle

            if (ParentSize != -Vector2.one) {

                float SizeWidth = ParentSize.x - Left - Right;                                      // Calculate dimensions of Element;
                float SizeHeight = ParentSize.y - Top - Bottom;

                RectTransform.offsetMin = Vector2.zero;                                             
                RectTransform.offsetMax = new Vector2(SizeWidth, SizeHeight);                       // Set dimensions 
                
                RectTransform.anchoredPosition = new Vector2(SizeWidth / 2 + Left, SizeHeight / 2 + Bottom);   // Anchored Position set automatically Left, Top, Right and Bottom
            }


        }

    }
Forth answered 20/12, 2018 at 19:14 Comment(0)
C
0

check the link it will help you

Correy answered 6/6, 2023 at 2:39 Comment(0)
T
0

Here’s my attempt at making functions to apply stretch anchors:

public static void SetStretchAnchorAll(RectTransform t)
{
    t.pivot = Vector2.one * 0.5f;
    t.anchorMin = Vector2.zero;
    t.anchorMax = Vector2.one;
    t.anchoredPosition = Vector2.zero;
    t.sizeDelta = Vector2.zero;
}

public static void SetStretchAnchorLeft(RectTransform t)
{
    SetStretchAnchorToSide(t, Vector2.up);
}
public static void SetStretchAnchorRight(RectTransform t)
{
    SetStretchAnchorToFarSide(t, Vector2.right);
}
public static void SetStretchAnchorTop(RectTransform t)
{
    SetStretchAnchorToFarSide(t, Vector2.up);
}
public static void SetStretchAnchorBottom(RectTransform t)
{
    SetStretchAnchorToSide(t, Vector2.right);
}
static void SetStretchAnchorToSide(RectTransform t, Vector2 stretch)
{
    var old_size = t.rect.size;
    var perpendicular = Vector2.one - stretch;
    t.pivot = stretch * 0.5f;
    t.anchorMin = Vector2.zero;
    t.anchorMax = stretch;
    t.anchoredPosition = Vector2.zero;
    t.sizeDelta = Vector2.Scale(perpendicular, old_size);
}
static void SetStretchAnchorToFarSide(RectTransform t, Vector2 stretch)
{
    var old_size = t.rect.size;
    t.pivot = (Vector2.one + stretch) * 0.5f;
    t.anchorMin = stretch;
    t.anchorMax = Vector2.one;
    t.anchoredPosition = Vector2.zero;
    t.sizeDelta = Vector2.Scale(stretch, old_size);
}
Tilda answered 13/8, 2020 at 17:50 Comment(0)
C
0

allenallenallen explained very well how the RectTransform and its anchor values work.
I want to add, that you need to use the following line of code, to modify the position of your object:

panelRectTransform.anchoredPosition3D =  new Vector3(0f, 0f, 0f);

_
(Originally you had to use “.anchoredPosition” (Vector2) to do this. But before that you also had to use “.localPosition” (Vector3) to make sure you get the expected z-value.)

Consequential answered 14/8, 2020 at 14:11 Comment(0)
W
0

This solution works Set a RectTranform's pivot without changing its position - Questions & Answers - Unity Discussions

Posting this comment so more people can find the answer easily.

Use the ones in the bottom comments or the code I’m going to paste below. I’m posting 2 functions that do the same thing, both work(SetPivot and SetPivot2), and take into account scale and rotation, just slightly different method of doing it.

public static void SetPivot(this RectTransform target, PivotPresets preset)
        {
            target.SetPivot(GetVector2FromPivot(preset));
        }
        
        public static void SetPivot2(this RectTransform target, PivotPresets preset)
        {
            target.SetPivot2(GetVector2FromPivot(preset));
        }
        /// <summary>
        /// Point of this is to change the pivot, without moving the object. Method 1
        /// </summary>
        public static void SetPivot(this RectTransform target, Vector2 pivot)
        {
            if (target == null) return;
            var offset=pivot - target.pivot;
            offset.Scale(target.rect.size);
            var wordlPos= target.position + target.TransformVector(offset);
            target.pivot = pivot;
            target.position = wordlPos;
        }
        /// <summary>
        /// Point of this is to change the pivot, without moving the object. Method 2
        /// </summary>
        public static void SetPivot2(this RectTransform rect, Vector2 pivot)
        {
            if (rect == null) return;
            Vector3 deltaPosition = rect.pivot - pivot;    // get change in pivot
            deltaPosition.Scale(rect.rect.size);           // apply sizing
            deltaPosition.Scale(rect.localScale);          // apply scaling
            deltaPosition = rect.transform.localRotation * deltaPosition; // apply rotation
     
            rect.pivot = pivot;                            // change the pivot
            rect.localPosition -= deltaPosition;           // reverse the position change
        }

public enum PivotPresets
    {
        TopLeft,
        TopCenter,
        TopRight,
 
        MiddleLeft,
        MiddleCenter,
        MiddleRight,
 
        BottomLeft,
        BottomCenter,
        BottomRight,
    }

public static Vector2 GetVector2FromPivot(PivotPresets preset)
        {
            switch (preset)
            {
                case (PivotPresets.TopLeft):
                {
                    return new Vector2(0, 1);
                }
                case (PivotPresets.TopCenter):
                {
                    return new Vector2(0.5f, 1);
                }
                case (PivotPresets.TopRight):
                {
                    return new Vector2(1, 1);
                }
                case (PivotPresets.MiddleLeft):
                {
                    return new Vector2(0, 0.5f);
                }
                case (PivotPresets.MiddleCenter):
                {
                    return new Vector2(0.5f, 0.5f);
                }
                case (PivotPresets.MiddleRight):
                {
                    return new Vector2(1, 0.5f);
                }
                case (PivotPresets.BottomLeft):
                {
                    return new Vector2(0, 0);
                }
                case (PivotPresets.BottomCenter):
                {
                    return new Vector2(0.5f, 0);
                }
                case (PivotPresets.BottomRight):
                {
                    return new Vector2(1, 0);
                }
            }
            return default;
        }
Willodeanwilloughby answered 29/6, 2022 at 9:32 Comment(0)
S
0

public enum RectTransformAnchorHorizontal
{
Left,
Center,
Right,
Stretch
}
public enum RectTransformAnchorVertical
{
Top,
Middle,
Bottom,
Stretch
}
public static void SetAnchor(this RectTransform rt, RectTransformAnchorHorizontal anchorHorizontal, RectTransformAnchorVertical anchorVertical)
{
float anchorMinX =
anchorHorizontal == RectTransformAnchorHorizontal.Left ? 0 :
anchorHorizontal == RectTransformAnchorHorizontal.Center ? 0.5f :
anchorHorizontal == RectTransformAnchorHorizontal.Right ? 1 :
0;

        float anchorMinY =
            anchorVertical == RectTransformAnchorVertical.Top ? 1 :
            anchorVertical == RectTransformAnchorVertical.Middle ? 0.5f :
            anchorVertical == RectTransformAnchorVertical.Bottom ? 0 :
            0;

        float anchorMaxX =
            anchorHorizontal == RectTransformAnchorHorizontal.Left ? 0 :
            anchorHorizontal == RectTransformAnchorHorizontal.Center ? 0.5f :
            anchorHorizontal == RectTransformAnchorHorizontal.Right ? 1 :
            1;

        float anchorMaxY =
            anchorVertical == RectTransformAnchorVertical.Top ? 1 :
            anchorVertical == RectTransformAnchorVertical.Middle ? 0.5f :
            anchorVertical == RectTransformAnchorVertical.Bottom ? 0 :
            1;

        float pivotX =
            anchorHorizontal == RectTransformAnchorHorizontal.Left ? 0 :
            anchorHorizontal == RectTransformAnchorHorizontal.Center ? 0.5f :
            anchorHorizontal == RectTransformAnchorHorizontal.Right ? 1 :
            0.5f;

        float pivotY =
            anchorVertical == RectTransformAnchorVertical.Top ? 1 :
            anchorVertical == RectTransformAnchorVertical.Middle ? 0.5f :
            anchorVertical == RectTransformAnchorVertical.Bottom ? 0 :
            0.5f;

        rt.anchorMin = new Vector2(anchorMinX, anchorMinY);
        rt.anchorMax = new Vector2(anchorMaxX, anchorMaxY);
        rt.pivot = new Vector2(pivotX, pivotY);
    }
Statis answered 5/4, 2023 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.