- Home /
Trying to set RectTransform anchorposition in script
I am instantiating an empty game object in my script. I add a RectTransform component, and am trying to set its anchor position on the upper left corner. In the editor you just have to open the anchor presets and choose the position / direction you want to set it at.
I was wondering how you can do this via script. This is what I currently have:
GameObject Container;
Container = new GameObject();
Container.AddComponent<RectTransform>();
Container.GetComponent<RectTransform>().localPosition = new Vector3(0.0f, 0.0f, 0.0f);
I was wondering if anyone could help me with this. I have done some googling and looked into anchoredPosition as well as anchoredMin / anchoredMax, but I couldnt get any of them working.
Answer by hexagonius · Feb 18, 2016 at 07:05 AM
anchoredmin/ max seem to be correct. what you are missing is the code that makes your new gameobject a children of a canvas. without it a recttransform does not work. use SetParent with false parameter to do so
Answer by HardikMaru2001 · Feb 18, 2016 at 09:03 AM
Hi @Teekay,
You can set Anchor Preset through script using anchor points of RectTransform. Refer this 3 links,
1) http://docs.unity3d.com/ScriptReference/RectTransform-anchorMin.html 2) http://docs.unity3d.com/ScriptReference/RectTransform-anchorMax.html 3) http://docs.unity3d.com/ScriptReference/RectTransform-pivot.html Values are between 0-1.
Here is one example, if you want to set the anchor preset to top left then you have to set the Min(X,Y) to (0,1) and Max(X,Y) to (0,1).
Try and play with it, and you will get an idea of what value you have to set in order to get your result.