Thursday, November 1, 2018

2D Platformer Character 4 / 4 - Collectibles

Lets enable our cat to collect things. Add sprite of your choice (can be animated or not) to the scene (I used animated gems from here), add some kind of 2D collider to it and mark it as a trigger. Next, add this script to your player cat.
using UnityEngine;
 
public class Collector : MonoBehaviour
{
    // How many things we have collected
    public int collected;
 
    // What should happen if we enter trigger
    private void OnTriggerEnter2D(Collider2D collision)
    {
        // If it's collectible
        if (collision.gameObject.CompareTag("Collectible"))
        {
            // Destroy it
            Destroy(collision.gameObject);
 
            // Increase count of objects we collected
            collected++;
        }
    }
}
If you play the game now, cat should be able to collect objects you placed, and number of items collected should increse whenever you pick something. Hovewer, there is no way currently to tell player how many items they collected. Lets fix it by displaying number of items collected on the screen. Add UI->Text object to your scene. Notice it also created 'Canvas' object automatically. This is just an object that represents whole screen under which all UI elements will be placed. In the Scene View, Canvas and all UI elements are usually much larger than your game world, so if you have problems locating it, select Canvas object and press 'f' key, which should center 'Scene View' on Canvas and your New Text object.

Rename our 'New Text' object to 'Score' for clarity sake and place it wherever you want by using 'Rect Tool' (marked on upper left of corner the screenshot). Also make sure to set anchor correctly under Rect Transform. It tells unity to stick your UI element to one side of the screen, which is important if your screen will change sizes (without it, your element might end up outside of the screen if you make game window smaller for example). And finally, make sure default text is "0". Now we need to tell unity to update this text whenever we collect something. Update our Collector.cs script to look like this.
using UnityEngine;
using UnityEngine.UI;
 
public class Collector : MonoBehaviour
{
    // How many things we have collected
    public int collected;
 
    // Text UI for displaying score
    public Text score;
 
    // What should happen if we enter trigger
    private void OnTriggerEnter2D(Collider2D collision)
    {
        // If it's collectible
        if (collision.gameObject.CompareTag("Collectible"))
        {
            // Destroy it
            Destroy(collision.gameObject);
 
            // Increase count of objects we collected
            collected++;
 
            // Update our score
            score.text = collected.ToString();
        }
    }
}
Assign our 'Score' Game Object to Score property of Collector.cs script. Congratulations, your cat can now collect items :3

No comments:

Post a Comment