Hi, How do I modify the Preset from the Rect Transform's anchors by code? Thank you!

Hello, I’m trying to modify the anchor’s preset at runtime. If I do that in the inspector it’s ok, but I don’t know how to do it by code. I tried to modify the anchors Min and Max parameters, but it changes my image position and I don’t want that.
Thank you!

You use:

// g is the referenced gameObject that has this rectTransform on it.
Vector2 positionOnScreen = new Vector2 {200f,20f};
g.GetComponent <RectTransform> ().anchoredposition = positionOnScreen;

That is for setting the 2d position, you can also set it’s 3d position, anchors, and pivot all using that same GetComponent command. To set the Anchor for example we look here at the manual documentation for RectTransform : Link for RectTransform and we see that it’s variable is called anchorMax and there is another one called anchorMin. You would just set it the same way:

// In the documentation you can clearly see when you click on anchorMin, that it want's a Vector2 variable
//... it wants an X and a Y

Vector2 = myPersonalAnchorForTheTopLeft = new Vector2 (20f,20f);
g.GetComponent <RectTransform> ().anchorMin = myPersonalAnchorForTheTopLeft;

Remember that rectTransform… collider… scripts… lights…meshes… ALL OF this stuff that you put onto gameobject in your scene are called Components. Some of these components can be called directly; like: this.transform.position

I think RectTransform has to be called using the GetComponent command.

And then once you have located it’s reference, you can then not ONLY set values in here, and get the values from here…But, later you can also call functions and tell that RectTransform to do stuff if you want it to. ( more advanced )