Is there a way of setting anchors from script, but using values set from GUI (Center, Middle etc. without specifying number values)?
I dont think you can do that. But you can set them using the AnchorMin & AnchorMax (Both Vector2) properties of the rect transform. So thus
Bottom Left corner would be
X Y
Min=>[0,0]
Max=>[0,0]
Bottom Right corner would be
X Y
Min=>[1,0]
Max=>[1,0]
Top Left corner would be
X Y
Min=>[0,1]
Max=>[0,1]
Top Right corner would be
X Y
Min=>[1,1]
Max=>[1,1]
Center would be
X Y
Min=>[0.5,0.5]
Max=>[0.5,0.5]
So for example to set your anchor to top left corner :
transform.GetComponent<RectTransform>().AnchorMin = new Vector2(0,1);
transform.GetComponent<RectTransform>().AnchorMax = new Vector2(0,1);
Hope this helps.
Thank you very much Do you know if there is a way of achieving from script the effect as when setting anchors in inspector holding “alt”? I mean, to change position along with anchors, or should I calculate it manually?
TextAnchor is an enum, you should call it by ising TextAnchor.“seedocsforalltypes”
Using UnityEngine.UI;
public Text text;
text.alignment = TextAnchor.UpperLeft;
I wrote myself a pretty neat script to easily test whatever I need
SetAnchor.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SetAnchor : MonoBehaviour {
public float x = 0;
public float y = 0;
public float aminx = 0;
public float aminy = 0;
public float amaxx = 0;
public float amaxy = 0;
public float apivotx = 0;
public float apivoty = 0;
void Start()
{
setAnchor(this.GetComponent<RectTransform>(), this.transform.parent.GetComponent<RectTransform>());
}
private void Update()
{
setAnchor(this.GetComponent<RectTransform>(), this.transform.parent.GetComponent<RectTransform>());
}
private void setAnchor(RectTransform rectTransform1, RectTransform rectTransform2)
{
rectTransform1.anchoredPosition = new Vector2(x, y);
rectTransform1.anchorMin = new Vector2(aminx, aminy);
rectTransform1.anchorMax = new Vector2(amaxx, amaxy);
rectTransform1.pivot = new Vector2(apivotx, apivoty);
//rectTransform1.sizeDelta = rectTransform2.rect.size;
//rectTransform1.transform.SetParent(rectTransform2);
}
}
When you are done testing. Comment or Delete the Update Methode.