Tag Archives: collectables

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