Of course, the game wouldn't be fun without any challenges so we're going to add in the pipe-like obstacles that the player will also need to avoid.
rockGrass
and rockGrassDown
sprite and place it into the Assets/Sprites
folder from the Project tab.rockGrass
object into the world. Change its position to 0, -2.5, 0
. Then, add a Polygon Collider 2D component to it.rockGrassDown
object into the world. Change its position to 0, 2.5, 0
. Then, add a Polygon Collider 2D component to it.0,0,0
and then rename it to Obstacle
. Afterwards, drag and drop the two rockGrass
objects to it to become the Obstacle
object's children:RepeatingBehaviour
script does, except instead of repeating, we want to remove it so we can respawn. Create a new C# Script named ObstacleBehaviour
and use the following code for it:using UnityEngine; public class ObstacleBehaviour : RepeatingBackground { protected override void Offscreen(ref Vector3 pos) { Destroy(this.gameObject); } }
While it may not look like a lot, quite a lot is going on here. Note that instead of MonoBehaviour
to the right of the :
, we now have RepeatingBehaviour
. What this does effectively is have ObstacleBehaviour
inherit everything that the RepeatingBehaviour
class has. This means that all of the properties and functionality are included from the previous script. This will allow us to only write code to extend or override the behavior from the original. In this case, we want to destroy the obstacle when it goes off screen, so all we do is override the Offscreen
function (which we can only do if we made the function virtual earlier) to now destroy the game object this was attached to before.
For more information on inheritance and derived classes, check out https://msdn.microsoft.com/en-us/library/ms228387(v=vs.90).aspx.
Save the script, then attach the newly created script to the Obstacle
object, and set the Scroll Speed property to 5
.
At this point, the obstacle will now go off screen, and afterwards, it'll destroy itself automatically!