nix86
nix86

Reputation: 3037

I can't set localPosition of a UI element in Unity3D

I've just created a label dynamically and inserted it inside a canvas. I've also set the anchors and the pivot of the label. The problem is that I can't set the localPosition. I've tried to set it to (0f,0f), but Unity3D puts it at (0f, -380f), so that it goes to the center of the screen. The code is this one:

GameObject label = new GameObject ("mylabel");
    label.AddComponent<Text> ();
    label.transform.SetParent(transform);
    label.GetComponent<Text> ().text = "some long text";
    label.GetComponent<Text> ().font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
    label.GetComponent<Text> ().fontSize = 30;
    label.GetComponent<RectTransform> ().anchorMin = new Vector2 (0.5f, 1f);
    label.GetComponent<RectTransform> ().anchorMax = new Vector2 (0.5f, 1f);
    label.GetComponent<RectTransform> ().pivot = new Vector2 (0.5f, 1f);
    label.GetComponent<RectTransform> ().localPosition = new Vector2 (0f, 0f);//THIS DOESN'T SEEM TO BE WORKING, BECAUSE THE LABEL IS NOT PLACE AT (0F,0F) WHEN i RUN THE PROGRAM!!
    label.GetComponent<Text> ().color = Color.black;
    label.GetComponent<Text> ().horizontalOverflow = HorizontalWrapMode.Wrap;
    label.GetComponent<Text> ().verticalOverflow = VerticalWrapMode.Overflow;
    label.GetComponent<RectTransform> ().sizeDelta = new Vector2 (1000, 100);

In the code everything seems to work fine except the line where I try to set the localPosition because regardless of the value I insert I always end up seeing the label in the center of the screen.

Upvotes: 2

Views: 1509

Answers (1)

nix86
nix86

Reputation: 3037

I found out the mistake. Instead of setting localPosition I should have set anchoredPosition, so if you take the code above and replace localPosition with anchoredPosition it works.

Upvotes: 3

Related Questions