Search Unity

  1. The 2022.1 beta is now available for testing. To find out what's new, have a look at our 2022.1 beta blog post.
    Dismiss Notice
  2. Welcome to the Unity Forums! Please take the time to read our Code of Conduct here to familiarize yourself with the rules and how to post constructively.

PanelSettings ScaleWithScreenSize + MatchWidthOrHeight - add VisualElement at absolute position

Discussion in 'UI Toolkit' started by grizzlycorv, Feb 14, 2021.

  1. grizzlycorv


    Nov 9, 2018
    Hello everyone.

    I'm using the new UI Toolkit at Runtime, everything works great so far apart from a few known limitations.

    The ScaleMode of the PanelSettings I'm using are set to ScaleWithScreenSize and the ScreenMatchMode is set to MatchWidthOrHeight.

    I'm trying to add a VisualElement at an absolute location that I get via Camera.WorldToScreenPoint(position).

    Following is just an example of one of my tries...
    Code (CSharp):
    1.         Vector3 screenPointPosition = Camera.WorldToScreenPoint(position);
    2.         var viewPortPoint = Camera.ScreenToViewportPoint(screenPointPosition);
    3.         Vector2Int referenceResolution = new Vector2Int(Screen.width, Screen.height);
    5.         int screenX = (int)(viewPortPoint.x * referenceResolution.x);
    6.         int screenY = (int)(viewPortPoint.y * referenceResolution.y);
    I tried several ways to calculate the position but the position where the VisualElement is added is always incorrect. My understanding is that the automatic scaling by my PanelSettings is responsible for this - If I use different PanelSettings it works fine, but then of course the UI doesn't scale as I want it to.

    Has anyone already had this problem? Is there a solution or workaround for it?
  2. MousePods


    Jul 19, 2012
    I use this method:

    Code (CSharp):
    1.     public static float GetCanvasScaleFactor(PanelSettings panelSettings)
    2.     {
    3.         return ((float)Screen.width / panelSettings.referenceResolution.x) * (1 - panelSettings.match) + ((float)Screen.height / panelSettings.referenceResolution.y) * (panelSettings.match);
    4.     }
    grizzlycorv likes this.
  3. grizzlycorv


    Nov 9, 2018
    Wow, that was a fast reply and it works like a charm. Thank you!
    MousePods likes this.