简体   繁体   中英

Can I change a World Space canvas width to match screen?

I have a Unity2D orthographic projection game laid out on a World Space canvas. When I change aspect ratios, the UI elements get clipped off by the screen edges. I understand I could Screen Space to solve that, but that causes other issues. I need this canvas to be in World Space.

The attached image shows the layout in 18:9 in the Scene window. I changed the aspect to 4:3 in the Game window, then went back to the Scene window. You can see how the canvas will be clipped to 4:3. If I resize the canvas width to match the screen aspect everything is fine, but I need to do that in script to match the device aspect ratio, not just through the Inspector.

It looks like I can resize the canvas to match the 4:3 screen and all is well, but how do I do that in code?

在此处输入图片说明

The Canvas Scaler component is responsible for adjusting your UI to the correct Aspect Ratio. Since you are using World Space, the canvas scaler does not apply aspect ratio adjustments.

You could change your canvas' dimensions to your screen's resolution on Awake(). If your anchors are set properly, this could do the trick.

In Awake , set the width of the canvas based on the aspect ratio of the camera:

void Awake()
{
    RectTransform rt = GetComponent<RectTransform>();
    float canvasHeight = rt.rect.height;
    float desiredCanvasWidth = canvasHeight * Camera.main.aspect;
    rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, desiredCanvasWidth);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM