Looping background

I am making a 2D game with side scrolling. There are 3 different backgrounds and i want it to loop one after the other. Please help me with this.

Easiest solution: Just create as many background tiles as you will need for the whole level. As the duplicates are all using the same material this shouldn’t be a problem. If you don’t know how big your level is at compile time (e.g. endless running game) you can save a background set (all three backgrounds next to each other) as a prefab and use a trigger in the center of the second screen to trigger respawning the prefab. (and destroying the old one…)

That’s not the best approach to what you’re looking for. It might be much better to just have the background texture you want to loop in a plane, and do something like this:


public class planeMovement : MonoBehaviour {
    public Transform myCamera;
    public float backgroundSpeed = 1.0f;

    void Update() {
        Vector2 aux = renderer.material.mainTextureOffset;
	    aux += new Vector2(backgroundSpeed*cameraSpeed*Time.deltaTime,0);
	    renderer.material.mainTextureOffset = aux;

        Vector3 aux2 = new Vector3(camera.position.x,transform.position.y,transform.position.z);
        transform.position = aux2;

The script variables should be self-explanatory. You should drag and drop your camera from the inspector to assign the myCamera variable. Adjust the backgroundSpeed value to what you need.

To make the 3 backgrounds loop (answering your question in the comments), you should set the tiling x value at the plane’s material to 0.333 (assuming there are 3 backgrounds, otherwise the value would be 1/number of backgrounds) and the texture should contain the 3 backgrounds. One after another. That should do the trick (I’ve tried it and it works).

You should take into account that different screen sizes would need different background plane sizes, so you would need a little bit more of scripting to fix that (maybe changing the background plane’s scale on startup depending on the screen type, or even choosing different background textures so it won’t strech).

I hope it helped!