how to change background in unity 2d code example

Example 1: unity 2d swap out background image

//You can create a sprite and swap which sprite it is using currently.
//these can be set in editor
public GameObject sprite1;
public GameObject sprite2;

//put following code in function that changes sprites
//this sets both of these to be the opposite of their current state
//SetActive() will set the game object before it to the active state of the
//bool in the parameters.
//activeSelf returns the active state of the given game object
sprite1.SetActive(!sprite.activeSelf);
sprite2.SetActive(!sprite.activeSelf);

Example 2: unity set background image 2d

Plop your image into the scene as a sprite.
Resize the image.
Position the image into the horizon.
REMEMBER TO KEEP THE HEIGHT AND WIDTH RELATIVE TO EACH-OTHER OR THE IMAGE WILL DISTORT!

Another way is to add a UI Canvas and have the camera as the parent.
This way, you can look in any any direction and the background will be correct.
You can then position and resize the canvas.
You can also set its clipping to other objects so that it is in the background.