scroll background
Here's how to make a scrolling background/plane in Unity:
Method 1: Scrolling Texture (Material UV Offset) — Best for 2D backgrounds
using UnityEngine;
public class ScrollingBackground : MonoBehaviour
{
public float scrollSpeedX = 0.5f;
public float scrollSpeedY = 0f;
private Renderer rend;
void Start()
{
rend = GetComponent<Renderer>();
}
void Update()
{
float offsetX = Time.time * scrollSpeedX;
float offsetY = Time.time * scrollSpeedY;
rend.material.mainTextureOffset = new Vector2(offsetX, offsetY);
}
}
Setup: Attach this script to your Plane/Quad. Make sure the material's texture Wrap Mode is set to Repeat in the texture import settings.
Method 2: Moving the Object (Looping Plane) — Good for 3D ground scrolling
using UnityEngine;
public class LoopingGround : MonoBehaviour
{
public float speed = 5f;
public float resetPositionZ = -20f; // when to reset
public float startPositionZ = 20f; // where to reset to
void Update()
{
transform.Translate(Vector3.back * speed * Time.deltaTime);
if (transform.position.z <= resetPositionZ)
{
Vector3 pos = transform.position;
pos.z = startPositionZ;
transform.position = pos;
}
}
}
Tip: Use two planes side by side so there's no visible gap when one resets.
Method 3: Parallax Scrolling (2D Camera-Based)
using UnityEngine;
public class ParallaxBackground : MonoBehaviour
{
public float parallaxFactor = 0.5f; // 0 = moves with camera, 1 = fixed
private Transform cam;
private Vector3 lastCamPos;
void Start()
{
cam = Camera.main.transform;
lastCamPos = cam.position;
}
void Update()
{
Vector3 delta = cam.position - lastCamPos;
transform.position += new Vector3(delta.x * parallaxFactor, delta.y * parallaxFactor, 0);
lastCamPos = cam.position;
}
}
Quick Summary
| Method | Best For | Notes |
|---|---|---|
| UV Offset | 2D/3D textured scroll | Seamless, very performant |
| Moving Object | 3D endless runner | Needs 2+ planes to loop |
| Parallax | 2D side-scrollers | Creates depth effect |
For most cases, Method 1 (UV Offset) is the simplest and most performant option. Just make sure your texture's Wrap Mode is set to Repeat.
Comments