Posted August 21, 2025 by Dooshima Games
##endlessRunner ##unity2d ##c#
Step-by-Step Tutorial: Simple Endless Runner in Unity2D
using UnityEngine;
public class PlayerController: MonoBehaviour
{
public float jumpForce = 10f;
private Rigidbody2D rb;
private bool isGrounded;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isGrounded = false;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
isGrounded = true;
if (collision.gameObject.CompareTag("Obstacle"))
Debug.Log("Game Over!"); // Later replace with game over screen
}
}
Create a script GroundScroller.cs and attach it to your ground prefab. using UnityEngine;
public class GroundScroller: MonoBehaviour
{
public float speed = 5f;
private float groundWidth;
void Start()
{
groundWidth = GetComponent<SpriteRenderer>().bounds.size.x;
}
void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
if (transform.position.x < -groundWidth)
{
transform.position = new Vector2(transform.position.x + groundWidth * 2, transform.position.y);
}
}
}
Create ObstacleSpawner.cs and attach it to an empty GameObject in your scene. using UnityEngine;
public class ObstacleSpawner : MonoBehaviour
{
public GameObject obstaclePrefab;
public float spawnRate = 2f;
public float obstacleSpeed = 5f;
void Start()
{
InvokeRepeating(nameof(SpawnObstacle), 1f, spawnRate);
}
void SpawnObstacle()
{
GameObject obj = Instantiate(obstaclePrefab, transform.position, Quaternion.identity);
obj.AddComponent<Rigidbody2D>().gravityScale = 0;
obj.GetComponent<Rigidbody2D>().velocity = Vector2.left * obstacleSpeed;
Destroy(obj, 10f); // cleanup
}
}
When the player collides with an obstacle, stop the game. Update Player script: if (collision.gameObject.CompareTag("Obstacle"))
{
Time.timeScale = 0; // pause game
Debug.Log("Game Over!");
}
Add a Restart Button in UI that reloads the scene: using UnityEngine;
using UnityEngine.SceneManagement;
public class GameOverManager : MonoBehaviour
{
public void RestartGame()
{
Time.timeScale = 1;
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}