How do I set the aspect ratio of the game viewport manually?
Thanks, Elliot Bonneville
How do I set the aspect ratio of the game viewport manually?
Thanks, Elliot Bonneville
If you want to set the viewport's aspect ratio through letterboxing or pillarboxing (that is, without changing your game window's resolution), first add a camera script with the following code:
// Use this for initialization
void Start ()
{
// set the desired aspect ratio (the values in this example are
// hard-coded for 16:9, but you could make them into public
// variables instead so you can set them at design time)
float targetaspect = 16.0f / 9.0f;
// determine the game window's current aspect ratio
float windowaspect = (float)Screen.width / (float)Screen.height;
// current viewport height should be scaled by this amount
float scaleheight = windowaspect / targetaspect;
// obtain camera component so we can modify its viewport
Camera camera = GetComponent<Camera>();
// if scaled height is less than current height, add letterbox
if (scaleheight < 1.0f)
{
Rect rect = camera.rect;
rect.width = 1.0f;
rect.height = scaleheight;
rect.x = 0;
rect.y = (1.0f - scaleheight) / 2.0f;
camera.rect = rect;
}
else // add pillarbox
{
float scalewidth = 1.0f / scaleheight;
Rect rect = camera.rect;
rect.width = scalewidth;
rect.height = 1.0f;
rect.x = (1.0f - scalewidth) / 2.0f;
rect.y = 0;
camera.rect = rect;
}
}
Then, to render the "black bar" region of the screen, add a second camera to your scene, set its depth value to -2 (so it's rendered underneath the main camera), set the camera's Clear Flags to "Solid Color", set the Culling Mask to "Nothing", and set the Background color to black (or whatever color you want).
If you do this, watch out for a bug in Unity 3.0 where it reports the wrong resolution when the game is run from the editor and the game window isn't showing (either because it's closed or because it's covered by another window in the same tab group).
If all you want to do is set the screen's resolution, call the `Screen.SetResolution()` function. For instance, to set the screen to 1024x768 full screen you would call `Screen.SetResolution(1024, 768, true)`. Be careful, though: If the fullscreen parameter to `SetResolution()` is true and you pass it a resolution that's not supported by the user's video card, Unity will pick whatever resolution it thinks is closest, possibly with the wrong aspect ratio, instead of the one you indicated.