Tag Archives: ui

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;
  }
}

Getting started with Unity

Welcome to the Unity 3D Game Development tutorial series! Unity is a game engine for building 2D and 3D games that can be played on a range of different platforms including Mac, Windows, iOS, Android, and more.

Unity allows you to create game objects and environments and then program your games using the C# (C Sharp) and JavaScript programming languages (you can also code in Boo but it is no longer documented by Unity 5). You can choose which language you would like to use but in these tutorials we will work with C#.

To get started with Unity, watch the video below. Make sure you also check out the Unity FAQ & Tips page to get the most out of Unity. Make sure you also get used to using Unity keyboard shortcuts so that you can work faster in Unity.

You can download the Unity game engine for Mac or Windows here. The Personal Edition is free to use and that is what will be used in these tutorials. When you install Unity, make sure you also include any standard assets, demo projects and files, and MonoDevelop in the installation.