2015-07-10 42 views
1

我剛剛創建了一個動態標籤並將其插入到畫布中。我還設置了錨點和標籤的樞軸。問題是我無法設置localPosition。我嘗試將它設置爲(0f,0f),但Unity3D將它放在(0f,-380f)處,以便它進入屏幕的中心。該代碼是這一個:我無法在Unity3D中設置UI元素的localPosition

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); 

在代碼中的一切似乎除了行工作得很好,我嘗試設置localPosition因爲無論我插入我總是最後看到標籤中的中心價值屏幕。

+0

在父畫布對象中沒有網格佈局 – nix86

+0

如果您將'localPosition'例如更改爲'(0f,100f)'標籤真的停留在同一個地方嗎? – Nikita

+0

是的,它總是留在中心 – nix86

回答

1

我發現了這個錯誤。而不是設置localPosition,我應該設置anchoredPosition,所以如果你拿上面的代碼並用anchoredPosition替換localPosition,它就可以工作。