Scrolling Background in Unity using Code
You need a scrolling background in order to give the illusion of movement? Well, here’s a quick and simple solution. However, I want you to be aware that doing it this way has many flaws and the same thing can be done better using Shaders.
Let me explain the pros and cons first:
- Quick and easy
- Can be done without any prior knowledge of Shader Graph or Shader Code
- Values to make it work are hard coded and specific to the sprite used as a BG
- Not flexible or dynamic if you needed to switch the BGs
Now, let’s get to it!
First things first, we need to make sure that the texture/sprite is bigger than the Game Screen by a generous margin and that it is seamless. There are many ways to do this using things like Photoshop or Photopea, but I’ll leave this link here which is my favourite video showing a quick way to do so.
Now, we can place two of them into the scene:
Next, set the Second Piece to (0,0,0) and determine what distance we need in order to perfectly tile the First Piece onto the Second Piece. In my case, it is when y = 21.6.
This will be our “Vertical Difference”. This is what we’ll use to offset each piece so that they tile properly. I have the script on a parent object for the pieces so I only need to create one.
The next variable we need to find is the “Minimum Height”. The height where the piece on the bottom is no longer visible by the camera so we can teleport it above the piece above it in order to create a loop like this. That sounds weird typed out so here’s a visual reference:
This is where we need the pieces to be larger than the Game Screen, so that the player doesn’t see each piece being teleported. In my case it is at y = -15.
Now we can get to the code. The logic is this: “When the y value of the piece drops below our Minimum Height then we place it above the previous piece by our Vertical Difference.”
In code, that looks like this:
It’s pretty straight forward. The only left to do now is to scroll them downwards in order to give the illusion of movement! Which can be done easily in the Update function.
And here’s the full script for easy reference:
Just make sure to set the proper Transforms into the script and you’re good to go!