Skip to content

Instantly share code, notes, and snippets.

@satanas
Last active December 29, 2023 01:07
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satanas/5766d9d9d34f94be25cb0f85ffc50ad1 to your computer and use it in GitHub Desktop.
Save satanas/5766d9d9d34f94be25cb0f85ffc50ad1 to your computer and use it in GitHub Desktop.
Scrolling Background in Unity

Scrolling Background in 2D

  1. Select the original Texture (not the GameObject).
  2. Change Texture Type to Sprite (2D and UI).
  3. Change Wrap Mode to Repeat.
  4. Click Apply.
  5. Create a Quad object: GameObject -> 3D Object ->Quad.
  6. Scale the Quad to the size you want.
  7. Create a light: GameObject->Light->Directional Light.
  8. Adjust the light intensity to whatever you like.
  9. Drag your Texture/Sprite to the Quad in the Scene View.

Now, create your script:

public class OffsetScrolling : MonoBehaviour {
    public float scrollSpeed;

    private Renderer renderer;
    private Vector2 savedOffset;

    void Start () {
        renderer = GetComponent<Renderer> ();
    }

    void Update () {
	float x = Mathf.Repeat (Time.time * scrollSpeed, 1);
	Vector2 offset = new Vector2 (x, 0);
	renderer.sharedMaterial.SetTextureOffset("_MainTex", offset);
    }
}

Note: For 2D, you can also use a Plane and the code above should work fine.

References:

@offbeatside
Copy link

Thank you very much for sharing!

@satanas
Copy link
Author

satanas commented Aug 13, 2019

@offbeatside I'm glad it was helpful for you 😄

@teo-sk
Copy link

teo-sk commented Nov 14, 2019

Thank you, just used it in a project, very useful 👍

@satanas
Copy link
Author

satanas commented Nov 27, 2019

@teo-sk 🙌

@ToastBrot188
Copy link

it diden worked pls help

@hend7h
Copy link

hend7h commented Feb 15, 2021

thank u

@shpulinn
Copy link

Thank you! Works great with a Quad and Plane in 2D scenes.

@zangad
Copy link

zangad commented Jan 13, 2022

Nice, thank you! Exactly what I needed. Quick note: you can change the direction of the moving texture by giving it a negative scrollSpeed.

@Jiaquarium
Copy link

On URP, the Lit shader main texture map is called "_BaseMap" btw.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment