Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

UI Elements Misplaced When Created From Command Line

Discussion in 'UGUI & TextMesh Pro' started by SinCL, Nov 28, 2020.

  1. SinCL

    SinCL

    Joined:
    Sep 14, 2020
    Posts:
    6
    When trying to create a UI Text for a template project using the Unity command line option -executeMethod, the position of the Text object was misplaced at (-320, -240). What am I missing?

    Here is the code snippets:

    %EDITOR_PATH% -batchmode -projectPath %PROJECT_PATH% -executeMethod MyClass.MyMethod -quit


    Code (CSharp):
    1.  
    2.  
    3. private static void MyMakeUIMethod()
    4. {
    5.         // Called from MyMethod
    6.         // create canvas game object
    7.         GameObject canvasObject = new GameObject("Canvas");
    8.         Canvas canvasComponent = canvasObject.AddComponent<Canvas>();
    9.         canvasComponent.renderMode = RenderMode.ScreenSpaceOverlay;
    10.         canvasObject.AddComponent<CanvasScaler>();
    11.         canvasObject.AddComponent<GraphicRaycaster>();
    12.         Vector2 canvasPos = canvasObject.GetComponent<RectTransform>().position;
    13.         float hWidth = canvasObject.GetComponent<RectTransform>().rect.width * 0.5f;
    14.         float hHeight = canvasObject.GetComponent<RectTransform>().rect.height * 0.5f;
    15.         // create score text
    16.         GameObject scoreTextObject = new GameObject("ScoreText");
    17.         scoreTextObject.transform.parent = canvasObject.transform;
    18.         Text text = scoreTextObject.AddComponent<Text>();
    19.         text.text = "Score: 0";
    20.         text.fontSize = 36;
    21.         text.color = Color.white;
    22.         text.alignment = TextAnchor.MiddleLeft;
    23.         // position the text
    24.         RectTransform rectTransform;
    25.         const float margin = 10.0f;
    26.         rectTransform = text.GetComponent<RectTransform>();
    27.         rectTransform.anchorMin = new Vector2(0.0f, 1.0f);
    28.         rectTransform.anchorMax = new Vector2(0.0f, 1.0f);
    29.         rectTransform.pivot = new Vector2(0.5f, 0.5f);
    30.         float w = 200.0f;
    31.         float h = 50.0f;
    32.         rectTransform.sizeDelta = new Vector2(w, h);
    33.         rectTransform.SetPositionAndRotation(new Vector2(canvasPos.x - hWidth + 0.5f*w + margin, canvasPos.y + hHeight - 0.5f*h - margin), Quaternion.identity);
    34. }
     
  2. SinCL

    SinCL

    Joined:
    Sep 14, 2020
    Posts:
    6
    A search turns up this old link: UI positioning problem - Unity Answers
    It looks like the problem can be avoided using anchoredPosition instead of SetPositionAndRotation:

    rectTransform.anchoredPosition = new Vector2(offsetX, offsetY);