Skip to content

Unity Parallax Background

Learn how to make Parallax Background in Unity.


csharp
using UnityEngine;
public class ParallaxBackground : MonoBehaviour
{
    private float length, startPos;
    public GameObject cam;
    public float parallaxEffect;
    
    private void Start()
    {
        startPos = transform.position.x;
        length = GetComponent().bounds.size.x;
    }
    
    private void FixedUpdate()
    {
        float temp = (cam.transform.position.x * (1 - parallaxEffect));
        float dist = (cam.transform.position.x * parallaxEffect);
        
        transform.position = new Vector3(startPos + dist, transform.position.y, transform position.z);
        
        if (temp > startPos + length) startPos += length;
        else if (temp < startPos - length) startPos -= length;
    }
}

Setup Scene

Under the Camera object, create a parent object that will hold our backgrounds and place the backgrounds inside it.

In the example, there are 5 backgrounds, so I set the Order in Layer values in Additional Settings in the following order: 5, 4, 3, 2, 1.

Select all 5 backgrounds and duplicate them. Set the X value to 18 for the duplicates, then duplicate them again and set the X value to -18.

Group each copy under the main object.

Assign the ParallaxBackground script we created to the main objects. Assign the camera to the Cam field and set the Parallax Effect as follows:

  1. For close: 0
  2. For mid: 0.3
  3. For far-mid: 0.45
  4. For far: 0.5
  5. For real far: 0.7

The images in this article were created by penusbmic.

Game Developer Ali Şahan Yalçın