Tag Archives: unity

Adding collectables and scoring to a 2D game in Unity

This tutorial explains how to add collectables and scoring to a 2D game in Unity. We will use the LevelManager script and CoinScript script from previous tutorials to improve the existing coin counting system, and we will also add more coins with different values. In the next tutorial, we will add a UI to display the number of coins on screen to the user.

Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the CoinScript script.

using UnityEngine;
using System.Collections;

public class CoinScript : MonoBehaviour {
  private LevelManager gameLevelManager;
  public int coinValue;

  // Use this for initialization
  void Start () {
    gameLevelManager = FindObjectOfType<LevelManager> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  void OnTriggerEnter2D(Collider2D other){
    if(other.tag == "Player"){
      gameLevelManager.AddCoins(coinValue);
      Destroy (gameObject);
    }
  }
}

Here is the sample C# code for the LevelManager script. The score won’t be displayed on screen until we add the UI Text element in the next tutorial.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;
  public int coins;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    StartCoroutine ("RespawnCoroutine");
  }

  public IEnumerator RespawnCoroutine(){
    gamePlayer.gameObject.SetActive (false);
    yield return new WaitForSeconds (respawnDelay);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }

  public void AddCoins(int numberOfCoins){
    coins += numberOfCoins;
  }
}

Next tutorial: Adding a UI to display the score

Adding a UI to display the score in a 2D game with Unity

This tutorial continues on from the previous tutorial on adding collectables and scoring to a 2D Unity game. In the previous tutorial, we improved the points scoring system and added collectables (coins) of different values).

In this tutorial we will add a UI (user interface) which will display the number of coins collected to the user. The LevelManager script will be responsible for displaying and updating the score text on screen. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the LevelManager script.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;
  public int coins;
  public Text coinText;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
    coinText.text = "Coins: " + coins;
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    StartCoroutine ("RespawnCoroutine");
  }

  public IEnumerator RespawnCoroutine(){
    gamePlayer.gameObject.SetActive (false);
    yield return new WaitForSeconds (respawnDelay);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }

  public void AddCoins(int numberOfCoins){
    coins += numberOfCoins;
    coinText.text = "Coins: " + coins;
  }
}

Adding a particle system to a 2D game in Unity

In this tutorial we will add a particle system to a 2D game in Unity. Particle systems emit particles in a game and can be used for adding a variety of effects like fire sparks, smoke, rain, and fog. We will use a particle system to emit spark effects.

Watch the video below to see how you can add particle systems to your own 2D game.

Next tutorial: Adding collectables and scoring

Adding a delay to respawn in a 2D Unity game

This tutorial continues on from the previous tutorials on setting up a fall detectoradding checkpoints, adding the ability to respawn the player, and adding a Level Manager to control respawning in a 2D game.

In this tutorial, we will use the Level Manager to control respawns and we will add a delay to respawns. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the PlayerController script.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;
  public Vector3 respawnPoint;
  public LevelManager gameLevelManager;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
    respawnPoint = transform.position;
    gameLevelManager = FindObjectOfType<LevelManager> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "FallDetector") {
      gameLevelManager.Respawn();
    }
    if (other.tag == "Checkpoint") {
      respawnPoint = other.transform.position;
    }
  }
}

Here is the sample C# code for the LevelManager script.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    StartCoroutine ("RespawnCoroutine");
  }

  public IEnumerator RespawnCoroutine(){
    gamePlayer.gameObject.SetActive (false);
    yield return new WaitForSeconds (respawnDelay);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }

}

Next tutorial: Particle systems in 2D Unity games

Setting up a Level Manager in a 2D Unity game

This tutorial continues on from the previous tutorials on setting up a fall detectoradding checkpoints, and adding the ability to respawn the player in a 2D game.

In this tutorial you will learn how to set up a Level Manager in a 2D platform game in Unity. The Level Manager will be used in the next tutorial to control player respawn and to add a delay to respawning. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the LevelManager script up to the point shown in the video above.

using UnityEngine;
using System.Collections;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    gamePlayer.gameObject.SetActive (false);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }
}

Here is the sample C# code for the PlayerController script up to the point shown in the video above.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;
  public Vector3 respawnPoint;
  public LevelManager gameLevelManager;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
    respawnPoint = transform.position;
    gameLevelManager = FindObjectOfType<LevelManager> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "FallDetector") {
      gameLevelManager.Respawn();
    }
    if (other.tag == "Checkpoint") {
      respawnPoint = other.transform.position;
    }
  }
}

Next tutorial: Adding a delay to player respawn

Respawn the player in a 2D Unity game

This tutorial continues on from the previous two tutorials on setting up a fall detector and adding checkpoints to a game. In the previous two tutorials, we set up the game with a fall detector and added checkpoints in the 2D scene. In this tutorial, we will allow the player to respawn at checkpoints in the game when the player falls off a platform or off the map. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the PlayerController script up to the point shown in the video above. This script will be modified in the next tutorial after adding a Level Manager to the game.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;
  public Vector3 respawnPoint;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
    respawnPoint = transform.position;
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "FallDetector") {
      transform.position = respawnPoint;
    }
    if (other.tag == "Checkpoint") {
      respawnPoint = other.transform.position;
    }
  }

}

Here is the sample C# code for the CheckpointController script that is attached to each checkpoint to change their flag colour sprite when reached by the player.

using UnityEngine;
using System.Collections;

public class CheckpointController : MonoBehaviour {

  public Sprite redFlag;
  public Sprite greenFlag;
  private SpriteRenderer checkpointSpriteRenderer;
  public bool checkpointReached;

  // Use this for initialization
  void Start () {
    checkpointSpriteRenderer = GetComponent<SpriteRenderer> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "Player") {
      checkpointSpriteRenderer.sprite = greenFlag;
      checkpointReached = true;
    }
  }
}

Next tutorial: Setting up a Level Manager

Adding checkpoints to a 2D Unity game

This tutorial explains how to add checkpoints to a 2D game so that we can respawn the player back to a checkpoint when the player falls off a platform or off the map. This continues on from the previous tutorial on setting up the fall detector and will be completed when we add the ability to respawn in the next tutorial.

Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the CheckpointController script.

using UnityEngine;
using System.Collections;

public class CheckpointController : MonoBehaviour {

  public Sprite redFlag;
  public Sprite greenFlag;
  private SpriteRenderer checkpointSpriteRenderer;
  public bool checkpointReached;

  // Use this for initialization
  void Start () {
    checkpointSpriteRenderer = GetComponent<SpriteRenderer> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "Player") {
      checkpointSpriteRenderer.sprite = greenFlag;
      checkpointReached = true;
    }
  }
}

Next tutorial: Respawn the player

Setting up a fall detector in a Unity 2D game

This tutorial explains how to set up a fall detector in a Unity 2D game that detects when the player has fallen off a platform or off the map and respawns the player back to a checkpoint. This will be covered across three tutorials. We will look at how to add checkpoints in the next tutorial.

Sample code

Here is the sample C# code for the PlayerController script up to the point shown in the above video. This script will be completed in the next two tutorials.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "FallDetector") {
      // what will happen when the player enters the fall detector code (this will be added later)
    }
    if (other.tag == "Checkpoint") {
      respawnPoint = other.transform.position;
    }
  }

}

Next tutorial: Adding checkpoints in the game

Stopping the player from sticking to the edge of platforms and walls in a 2D Unity game

This tutorial will show you a quick fix for stopping the player from sticking to the edge of platforms and walls in your 2D Unity game.

Next tutorial: Setting up a fall detector

Making the camera follow the player in a 2D Unity game with code

This tutorial will show you how to write a script in C# code that will make the camera follow the player in a 2D Unity game. Watch the video below and then scroll down for the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

  public GameObject player;
  public float offset;
  private Vector3 playerPosition;
  public float offsetSmoothing;

  // Use this for initialization
  void Start () {
  
  }
  
  // Update is called once per frame
  void Update () {
    playerPosition = new Vector3 (player.transform.position.x, transform.position.y, transform.position.z);
    if (player.transform.localScale.x > 0f) {
      playerPosition = new Vector3 (playerPosition.x + offset, playerPosition.y, playerPosition.z);
    }
    else {
      playerPosition = new Vector3(playerPosition.x - offset, playerPosition.y, playerPosition.z);
    }

    transform.position = Vector3.Lerp (transform.position, playerPosition, offsetSmoothing * Time.deltaTime);
  }
}

Next tutorial: Stopping the player from sticking to the edge of platforms and walls

Flipping the player with code in a 2D Unity game

This tutorial will show you how to flip your 2D game’s player sprite in Unity with C# code so that the player can turn and face the direction in which it is running, walking, or jumping.

Watch the video and then scroll down for the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }
}

Next tutorial: Making the camera follow the player with code

Controlling 2D player animations with C# code in Unity

In this tutorial, you will learn how to control player animations in your 2D game with C# code in Unity. Watch the video below and then scroll down for the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }
}

Next tutorial:  Flipping the player with code

Creating animations for the player sprite in a 2D Unity game

In this tutorial, you will learn how to create idle, walk/run, and jump animations for your 2D player in Unity. In the next tutorial we will set up the player animation controller.

Next tutorial: Setting up the player animation controller