How to Keep Score in UnityA Basic Game Tutorial

Author Waldo
Published June 15, 2019

In this tutorial I am going to show you how to keep track of a players score by showing you how to make a basic game in Unity.

Video Walkthrough

  • 0:55 - Adding Colliders and RigidBodies to our objects
  • 1:48 - Downloading resources from PressStart website
  • 2:15 - Creating a C# script
  • 2:40 - Creating a trigger collider
  • 3:15 - OnTriggerEnter2D
  • 4:10 - Creating a UI text element
  • 4:25 - Importing a Font from Google Fonts
  • 5:15 - Modifying the UI Text in C#
  • 6:00 - Setting up a Game Over Screen
  • 6:40 - Finished Product

Source Code for CupGame.cs

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

public class CupGame : MonoBehaviour{
    public int Score;
    public Text ScoreText;

    // Update is called once per frame
    void Update(){
        if(Score >= 5){
            YouWin();
        }
        
    }
    void YouWin(){
        ScoreText.text = "You Win!";
        Time.timeScale = 0f;
    }
    private void OnTriggerEnter2D(Collider2D other){
        Destroy(other.gameObject);
        AddScore();
    }

    void AddScore(){
        Score++;
        ScoreText.text = Score.ToString();
    }
}

Source Code for DeployBall.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DeployBall : MonoBehaviour{

    public GameObject asteroidPrefab;
    public float respawnTime = 0.3f;
    private Vector2 screenBounds;

    // Use this for initialization
    void Start() {
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
        StartCoroutine(asteroidWave());
    }
    private void spawnEnemy() {
        GameObject a = Instantiate(asteroidPrefab) as GameObject;
        a.transform.position = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), screenBounds.y * 1.5f);
    }
    IEnumerator asteroidWave() {
        while (true) {
            yield return new WaitForSeconds(respawnTime);
            spawnEnemy();
        }
    }
}

Source Code for Ball.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour {
    private Vector2 screenBounds;

    // Use this for initialization
    void Start() {
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));

    }

    // Update is called once per frame
    void Update() {
        if (transform.position.y < screenBounds.y * -2) {
            Destroy(this.gameObject);
        }
    }
}

Source Code for MoveObjectRBDesktop.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveObjectRBDesktop : MonoBehaviour {
    public GameObject objectToMove; //object that you want to move - drag in inspector
    public float moveSpeed = 20.0f; //adjust this based on how fast you want your object to move

    private Vector2 movement; 
    private bool TwoD = false;
    private Rigidbody rb;
    private Rigidbody2D rb2d;

    // Use this for initialization
    void Start(){
        if (objectToMove == null){
            //error reporting
            Debug.Log("Drag the object you want to move into the inspector under 'Object To Move'");
            objectToMove = gameObject;
        }
        if (objectToMove.GetComponent<Rigidbody2D>() != null){
            rb2d = objectToMove.GetComponent<Rigidbody2D>();
            TwoD = true;
        }else if (objectToMove.GetComponent<Rigidbody>() != null){
            rb = objectToMove.GetComponent<Rigidbody>();
        }else{
            Debug.Log("Assign either a RigidBody2D or RigidBody to your player object. Defaulting to RigidBody");
            rb = objectToMove.AddComponent<Rigidbody>();
        }
    }
    void Update(){
        movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
    }
    void FixedUpdate(){
        moveCharacter(movement);
    }
    void moveCharacter(Vector2 direction){
        if (TwoD){
            rb2d.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
        }else{
            rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
        }
    }
}

Source Code for ScreenBounds.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScreenBounds : MonoBehaviour {
    public Camera MainCamera; //be sure to assign this in the inspector to your main camera
    private Vector2 screenBounds;
    private float objectWidth;
    private float objectHeight;
    private bool isOrthographic;

    // Use this for initialization
    void Start(){
        if(MainCamera == null){
            MainCamera = Camera.main;
        }
        isOrthographic = MainCamera.orthographic;
        screenBounds = MainCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, MainCamera.transform.position.z));
        objectWidth = transform.GetComponent<SpriteRenderer>().bounds.extents.x; //extents = size of width / 2
        objectHeight = transform.GetComponent<SpriteRenderer>().bounds.extents.y; //extents = size of height / 2
    }

    // Update is called once per frame
    void LateUpdate(){
        Vector3 viewPos = transform.position;
        if(isOrthographic){
            viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x * -1 + objectWidth, screenBounds.x - objectWidth);
            viewPos.y = Mathf.Clamp(viewPos.y, screenBounds.y * -1 + objectHeight, screenBounds.y - objectHeight);
        }
        else{
            viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x + objectWidth, screenBounds.x * -1 - objectWidth);
            viewPos.y = Mathf.Clamp(viewPos.y, screenBounds.y + objectHeight, screenBounds.y * -1 - objectHeight);
        }
        transform.position = viewPos;
    }
}

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About