Showing posts with label aspect ratio. Show all posts
Showing posts with label aspect ratio. Show all posts

2019-04-04

How to make 2D Game that fit multiple resolution in Unity

There's a lot of screen resolution out there, how to make our UI objects (canvas) fit all resolution? One of the easiest solution is to envelope the canvas with borders, here's how you do it:

  1. Create a canvas object
  2. Set the Canvas Scaler to Scale with Screen Size
  3. Set the Reference Resolution to for example: 1080 x 800
  4. Set the Screen Match Mode to Match with Or Height
  5. Set the match to 1 if your current screen width is smaller, 0 if height is smaller
  6. Create an Image as background inside the Canvas
  7. Add Aspect Ratio Fitter script
  8. Set the Aspect Mode to Fit in Parent (so the UI anchor can be anywhere)
  9. Set the Aspect Ratio to 1080/800 = 1.35

Now you can add any UI elements inside the background Image.

Last piece is add this piece of script on the canvas' Awake method:

var canvasScaler = GetComponent<CanvasScaler>();
var ratio = Screen.height / (float) Screen.width;
var rr = canvasScaler.referenceResolution;
canvasScaler.matchWidthOrHeight = (ratio < rr.x / rr.y) ? 1 : 0;

This would ensure that the scaling/aspect ratio works correctly across any screen resolutions. There would be border on top-bottom if screen is taller than aspect ratio, and there would be border on left-right if screen is wider than aspect ratio.