Search Unity

PanelSettings ScaleWithScreenSize + MatchWidthOrHeight - add VisualElement at absolute position

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

  1. grizzlycorv

    grizzlycorv

    Joined:
    Nov 9, 2018
    Posts:
    19
    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);
    4.  
    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

    MousePods

    Joined:
    Jul 19, 2012
    Posts:
    811
    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

    grizzlycorv

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