Sprite resized to whole screen

I need to create a gameObject from code, so I do this:

GameObject background;
background = new GameObject("background");
background.AddComponent("SpriteRenderer");
background.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("background");

No I need to scale that sprite to cover the whole screen but I can’t do it. In Unity Scripting reference there’s a section called “Sprite Size” that is not there! How can I achieve that?

I use a static class that I’ve written based on other Unity answers to deal with this. Here’s my code (assumes an orthographic camera):

#pragma strict

public static class SpriteFunctions
{

	// If fitToScreenWidth is set to 1 then the width fits the screen width.
	// If it is set to anything over 1 then the sprite will not fit the screen width, it will be divided by that number.
	// If it is set to 0 then the sprite will not resize in that dimension.
	function ResizeSpriteToScreen(theSprite : GameObject, theCamera : Camera, fitToScreenWidth : int, fitToScreenHeight : int)
	{
	    var sr = theSprite.GetComponent(SpriteRenderer);
	    if (sr == null) return;
	 
	    theSprite.transform.localScale = Vector3(1,1,1);
	 
	    var width = sr.sprite.bounds.size.x;
	    var height = sr.sprite.bounds.size.y;
	 
	    var worldScreenHeight = theCamera.orthographicSize * 2.0;
	    var worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;
	 	
	 	if (fitToScreenWidth != 0)
	 	{
			theSprite.transform.localScale.x = worldScreenWidth / width / fitToScreenWidth;	
	 	}

	 	if (fitToScreenHeight != 0)
	 	{
			theSprite.transform.localScale.y = worldScreenHeight / height / fitToScreenHeight;
	 	}
	}
}

If this script (called SpriteFunctions) is in your scripts folder then all you need to do to resize the sprite is add this line to your code (cameraRef is a reference to the camera you want to fit the sprite to):

SpriteFunctions.ResizeSpriteToScreen(background, cameraRef, 1, 1);

The " 1, 1" parameters are for if you want the image to be smaller than full size. (background, cameraRef, 2, 2) for example would give half the width and height.

Hope this helps!

With a perspective camera:

    public SpriteRenderer spriteRenderer;
    public Camera camera;

    void OnGUI()
    {
        float spriteHeight = spriteRenderer.sprite.bounds.size.y;
        float spriteWidth = spriteRenderer.sprite.bounds.size.x;
        float distance = transform.position.z - camera.transform.position.z;
        float screenHeight = 2 * Mathf.Tan(camera.fieldOfView * Mathf.Deg2Rad / 2) * distance;
        float screenWidth = screenHeight * camera.aspect;
        transform.localScale = new Vector3(screenWidth / spriteWidth, screenHeight / spriteWidth, 1f);
    }

Working perfectly but there is a small problem. I using this method for my sprite, it’s good for y axis but doesn’t fit correctly on x axis.