How to make the background to fit with screen sizes without UI canvas (Unity 2D)

 


To make a background to fit all screen sizes without using a UI Canvas in Unity and it is a separate component, you can use a script to adjust the size and position of a 2D background component. Bellow a step-by-step guide about this topic:


Step 1: Create a 2D Background

1- Create a GameObject in the hierarchy to represent the 2D background.

2- Attach the image of the background to the SpriteRenderer in the inspector.


Step 2: Write a Script

1- Click on the add component in the inspector of the background GameObject and add new script, Here's a sample script that adjusts the size of the background based on the screen dimensions:



public class BackgroundFit : MonoBehaviour
{
    void Start()
    {
        // Call the function to scale the background on start
        ScaleBackground();
    }

    void ScaleBackground()
    {
        // Get the screen dimensions
        float screenHeight = Camera.main.orthographicSize * 2f;
        float screenWidth = screenHeight * Screen.width / Screen.height;

        // Print debug information
        Debug.Log("Screen Width: " + screenWidth + ", Screen Height: " + screenHeight);


        // Set the size of the sprite renderer
        SpriteRenderer spriteRenderer = GetComponent SpriteRenderer();
        if (spriteRenderer != null)
        {
            spriteRenderer.size = new Vector2(screenWidth, screenHeight);
        }
    }
}
**don't forget to add < > to the SpriteRenderer

Step 3: Configure Camera

Make sure your camera is set to orthographic projection. Adjust the orthographic size of the camera based on the desired view of your background.


Step 4: Test and Debug

Enter Play Mode in the Unity Editor and observe how the background adjusts to different screen sizes. Use the Game view to simulate different resolutions.



This script  adjusts the size of the SpriteRenderer based on the screen dimensions, making your 2D background responsive to various screen sizes.




Happy coding


Previous Post Next Post

Contact Form