Scale camera to fit screen size unity

Scale camera to fit screen size unity

My background and gameobjects are 2d sprites not UI images ,I want to know how to make my background scale with screen size and positions of 2d sprits on it don't change after building game (webGl) like scale canvas with screen size and anchor points in UI elements .
Before building the game 
After building 


Answer 1:

You can adjust the camera’s height so it scales with the width of the screen like so:

(Place this script on your Camera object)

public class MatchWidth : MonoBehaviour {

    // Set this to the in-world distance between the left & right edges of your scene.
    public float sceneWidth = 10;

    Camera _camera;
    void Start() {
        _camera = GetComponent<Camera>();

    // Adjust the camera's height so the desired scene width fits in view
    // even if the screen/window size changes dynamically.
    void Update() {
        float unitsPerPixel = sceneWidth / Screen.width;

        float desiredHalfHeight = 0.5f * unitsPerPixel * Screen.height;

        camera.orthographicSize = desiredHalfHeight;

If you’re using a perspective camera, then instead you’d use…

public float horizontalFoV = 90.0f;

// ...

void Update() {
   float halfWidth = Mathf.Tan(0.5f * horizontalFoV * Mathf.Deg2Rad);

   float halfHeight = halfWidth * Screen.height / Screen.width;

   float verticalFoV = 2.0f * Mathf.Atan(halfHeight) * Mathf.Rad2Deg;

   camera.fieldOfView = verticalFoV;

If you want to shrink your viewport to add letterboxes instead of showing additional height above/below, you can use the technique described in this answer.