Collectables
Collectables are a great way to add another objective to the game without directly affecting or changing the main objective. Players must complete each level, but in order to “100%” each level, they also need to collect every collectable.
Levels can have more than one type of collectable and collectables can be sparse, meaning there are very few to collect and they are scattered throughout each level, or they can be many, where there are potentially hundreds in a single level.
The following tutorial will show how to not only create a collectable, but also display the ‘count’ of the collectable in a User Interface.
Example GameManagerScript Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; // Required to use UI code in Unity
public class GameManagerScript : MonoBehaviour
{
private int collected; // Variable to keep track of how many have been collected
public Text collectedCounter; // Access the UI element to update what the player sees
void Start()
{
collected = 0; // At the start of the game, set collected to 0
}
// This function is called by a collectable when the player touches it
public void AddCollectable()
{
collected++; // Increase collected by 1
collectedCounter.text = collected.ToString(); // Update the user interface to display how many have been collected
}
}
Example Collectable Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collectable : MonoBehaviour
{
// This code runs when another Game Object has collided with it
private void OnTriggerEnter2D(Collider2D other)
{
// Checks to see if the name of the 'other' Game Object is "Player"
if (other.gameObject.name == "Player")
{
// Find the GameManager, access the GameManagerScript, then call 'AddCollectable()'
GameObject.Find("GameManager").GetComponent<GameManagerScript>().AddCollectable();
// After updating the Game Manager, destory the Collectable as its been 'picked up'
Destroy(gameObject);
}
}
}