Collectibles
Adding Collectibles
For collectibles, we can add any Sprite we’d like; in this tutorial, we will just make a GameObject that is a “Hexagon Flat-Top” in our Scene. Call the GameObject Collectible and add a Polygon Collider 2D.
Creating A Hexagon:
Notice that we’ve selected “Is Trigger” in the Polygon Collider 2D. A trigger allows you to detect collisions with objects while also being able to pass through them. This ensures that there is no unintended knockback from collecting.
Asset Organization
In the Assets window, go ahead and move all of your Sprites into the Materials folder.
Collectible Script
Add a script to the Collectible GameObject called Collectible
. This script will check if the Player collided with a Collectible and will update the score text.
using System;
using UnityEngine;
using UnityEngine.UI;
public class Collectible : MonoBehaviour
{
// A reference to your score text GameObject
public Text score;
// How much this particular collectible is worth (score)
public int scoreAmount;
// OnTriggerEnter2D instead of OnCollider2D because we checked "Is Trigger"
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
// Get the current score
int newScore = Int32.Parse(score.text) + scoreAmount;
// Save the current score to be used across multiple scenes.
PlayerPrefs.SetInt("score", newScore);
// Display the newScore in the UI
score.text = newScore.ToString();
// Make the Collectible disappear
Destroy(gameObject);
}
}
}
NOTE: If you use
TextMeshPro
instead of the legacyText
option, you should use this code instead:
- public Text score;
+ public TMPro.TextMeshProUGUI> score;
Connect the Text GameObject to the Collectible Script
- Drag the Score Text GameObject from the Hierarchy to the Collectible Script.
- Set the Score Amount to however much the collectible is worth.
- Test it out to see if it works.