< Back to Game Dev, Unity

Scaling Images to full screen in Unity

First, you’d put the image into your scene and give it a name, in this case “mainStage”. Then in the code:

float worldScreenHeight = Camera.main.orthographicSize * 2;
        float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;

        mainStage = GameObject.Find ("mainStage");
        SpriteRenderer sr = mainStage.GetComponent<SpriteRenderer>();

        mainStage.transform.localScale = new Vector2(
            worldScreenWidth / sr.sprite.bounds.size.x,
            worldScreenHeight / sr.sprite.bounds.size.y);

Though, this isn’t very practical as it would stretch your image. A more likely thing you’d want is to scale your background image to fit the width of the screen and then scale the height by the same amount. Is this case, transform would look something like:

mainStage.transform.localScale = new Vector2(
            worldScreenWidth / sr.sprite.bounds.size.x,
            worldScreenWidth * 4/3sr.sprite.bounds.size.y);

Here, I am using a 4:3 ratio so it goes full screen on something like an ipad

Leave a Reply

Your email address will not be published. Required fields are marked *