My game is on 2D landscape format and I wanted to scale my game screen size based on mobile device screen. I tried different code but to no avail. This is the first script I tried
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class MatchWidth : MonoBehaviour
{
public float sceneWidth = 25;
Camera _camera;
void Start()
{
_camera = GetComponent<Camera>();
}
void Update()
{
float unitsPerPixel = sceneWidth / Screen.width;
float desiredHalfHeight = 0.5f * unitsPerPixel * Screen.height;
camera.orthographicSize = desiredHalfHeight;
}
}
and the other script I tried
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeScreenSizeBasedonDevice : MonoBehaviour
{
// Use this for initialization
public float screenHeight = 1920f;
public float screenWidth = 1080f;
public float targetAspect = 9f / 16f;
public float orthographicSize;
private Camera mainCamera;
void Start()
{
mainCamera = Camera.main;
orthographicSize = mainCamera.orthographicSize;
float orthoWidth = orthographicSize / screenHeight * screenWidth;
orthoWidth = orthoWidth / (targetAspect / mainCamera.aspect);
Camera.main.orthographicSize = (orthoWidth / Screen.width * Screen.height);
}
}
The first one has a problem with its height it has a space on top and bottom and the second one zoom in too much. Can someone point where did i go wrong or who has a better code. I placed the both script on Main Camera
UPDATE I tried also Saif says in this link https://gamedev.stackexchange.com/questions/79546/how-do-you-handle-aspect-ratio-differences-with-unity-2d but the result is still the same as script 1. here is the pic:
What do I need to remove the space or margin at top or bottom
UPDATE 2
Solve the margin issue using this
void Start()
{
float screenWidth = GameManager.Instance.getScreenWidth();
float screenHeight = GameManager.Instance.getScreenHeight();
if (gameObject.name == "Cube")
{
transform.localScale = new Vector3(screenWidth / 4, screenHeight, -1);
transform.position = new Vector3(transform.position.x, 0, transform.position.z);
}
}
attached to gameobject to fit screen


