Collectables for the Player

How to create a Collectable System in Unity

In this article we will make the placeholder collectables actually collectable.

Setup Steps

We created 3 scripts. For the player, for the collectables and a UI Manager.

Create a UI Text game object
Attach the UI Manager script to the canvas
Attach the Collectable script to all collectables (use prefabs)
Make sure the collectables have a rigidbody and isTrigger is checked on the collider

Pseudocode — Collectable System Scripts

We will use all 3 scripts. The player script will hold the amount of collectables collected. The collectable script will check for collisions and if it is hit by the player it will tell the player script to increase the score. The player script will then tell the UI Manger to update the displayed number.

Collectable Script

private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
other.GetComponent<Player>().Collectable();
Destroy(this.gameObject);
}
}

Player Script

Handle to our UI Manager script assigned through the Inspector.

[SerializeField] private UIManager _uIManager;

Variable declared at the top to hold our score.

private int _collectables;

Our public method that is called from our Collectable script.

public void Collectable()
{
_collectables++;
_uIManager.UpdateCollectableText(_collectables);
}

UI Manager Script

Don’t forget at the top, because we need to use the UI library of the Unity engine.

using UnityEngine.UI;[SerializeField] private Text _collectableText;

public void UpdateCollectableText(int collectableCount)
{
_collectableText.text = "Balls: " + collectableCount;
}

--

--

--

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Using Github

A Beginners Guide to Go Programming

What happens when you type holbertonschool.com in your browser and press Enter

Ways to Make Money as a Developer — Job and Beyond

Introducing the Care.Protocol™

10 simple ways to make meetings more effective

Creating a Custom Feature Flagging Platform for Android with Firebase

Segwit2x Bugs Explained

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tristan Engel

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

More from Medium

Let’s create an Elevator in Unity

THM Linux Fundamentals PT 2

Configure Git on Windows

Differences between Static Libraries & Dynamic/Shared Libraries in C