- Home /
Position Text inside Canvas via Script
I have a simple clear 2d scene. There is a Main camera with the strength of 5 and a canvas to hold GUI elements.
I have a script attached to canvas which creates a GameObject and adds a Text component to the Canvase.
Now I would like to position Text inside Canvas. Canvas' width is 900 of some_units and it takes the whole Camera width (strength is 10 meters).
How do I do it programmaticaly? Don't quite understand how to convert 900 of some_units (prob pixels) into 10 meters.
EDIT: Added some code
...
RectTransform rectTransform = textGameObject.GetComponent<RectTransform>();
// Put anchor point into left upper corner
rectTransform.anchorMin = new Vector2(0, 1)
rectTransform.anchorMax = new Vector2(0, 1)
// Put pivot into left upper corner as well
rectTransform.pivot = new Vector2(0, 1)
// Position text at (0, 0) coordinate
textRectTransform.transform.position = new Vector2(0, 0); // doesn't work
textRectTransform.anchoredPosition = new Vector2(0, 0); // doesn't work
textRectTransform.localPosition = new Vector2(0, 0); // doesn't work
...
How the text can be posotioned in the left upper corner as well?
EDIT2: Ok, anchoredTransform actually worked.. being called during Start() it didn't set posotion correctly.
Answer by tigertrussell · Mar 19, 2015 at 01:21 PM
Note: all of this only applies to overlay mode only, not Screen Space and not World Space.
Unity's UI is rendered as an overlay onto your camera; there is no conversion to be done, the width of the Canvas is measured in pixels. The Canvas should cover your entire screen - and if you re-size the Player window, you should see your Canvas re-size the same way.
You Instantiate a prefab which contains a UnityEngine.UI.Text object, call SetParent on its Transform to parent it by something which is parented by the Canvas (or the Canvas itself) and you can position it using its RectTransform.
Make sense?
Thank you, it makes sense. But when I can't use Vector3 to adjust RectTransform's position, since Vector3 receives values in meters, while I have value (Canvas' width) in pixels. That is the problem.
$$anonymous$$g. I'd like to set Text's position to 450px. The code will look like: textRectTransform.transform.position = new Vector3(????)
Why do you say Vector3 is in meters? It's not Vector3 that measures in meters, it's a Transform. A RectTransform would measure in pixels. As long as your UnityEngine.UI.Text object is the child of a Canvas, the RectTransform will take over and handle everything in screen pixels, unless I am mistaken.
Unfortunately I am at work so I can't do any experiments to help you :\
When you say it "doesn't work," do you see the Text appearing somewhere else on the screen? Or is it possible that the RectTransform may have 0 (or very close to zero) size?
Answer by Rbrinks · Aug 30, 2020 at 02:29 AM
If this still isn't working for anyone, try changing position to localPosition. Worked for me anyway.
Your answer