Search Unity

Size and positioning based on screen width and height

Discussion in '2D' started by bil_unity967, Feb 12, 2020.

  1. bil_unity967

    bil_unity967

    Joined:
    Feb 12, 2020
    Posts:
    6
    Hi,

    I'm used to program games based on the screen width and height.
    What I do for portrait games is calculate the size of a sprite based on the width of the screen.
    Example: I need a square taking about 1/18 of the screen. I just make the sprite width a screenSizeWidth /18 for both width and height.

    In was Unity it was hard to find how to get screenWidth and screenHeight based on screen size.
    But I found out and here is how it is done
    Code (CSharp):
    1. Vector2 topRightCorner = new Vector2(1, 1);
    2.         Vector2 edgeVector = Camera.main.ViewportToWorldPoint(topRightCorner);
    3.         screenWidth = edgeVector.x * 2;
    4.         screenHeight = edgeVector.y * 2;
    Now I can use that on gameobjects using localscale
    For the example of 1/18 I can do new Vector3(screenWidth/18, screenWidth/18,gameobject.transform.localScale.z)

    Now I'm trying the same on a UI text. It also needs to scale to the same size of screenWidth/18.
    But when I use localScale it fails. When I use deltaSize. It fails.
    When I use Screen.width as base instead of the self calculated worldPoints screenWidth. It still fails.

    I tried canvas elements in both Worldspace and screenspace.
    I fail....

    I just need to put a text of the same size of the box. Just above the box. The box is a gameobject. the text UI.

    Anyone that can help me on this?

    kind regards
    Bil
     
  2. Primoz56

    Primoz56

    Joined:
    May 9, 2018
    Posts:
    369
    Use canvasscaler object and it will handle resizing/scaling for you. Then you just assume one fixed size screen eg. 800x600 and do everything based off that
     
  3. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Using the Canvas you shouldn't need to do any manual scripted math. RectTransforms are positioned relative to their parent object. If your Canvas has a CanvasScalar, then it will resize to fit the device screen based on the settings. If your button is a child of the Canvas, you can have the button's RectTransform change relative to the screen size. This is done using the Anchors on the RectTransform component.

    https://learn.unity.com/tutorial/ui-components