Build a 2D Platformer using Unity and C#

Lesson 5 of 7

Collectibles and Enemies

A platformer needs something to collect and something to avoid. Both come from the trigger and collision patterns you already know, applied to specific gameplay roles.

using UnityEngine;

public class Coin : MonoBehaviour
{
    public int value = 10;

    void OnTriggerEnter2D(Collider2D other)
    {
        if (!other.CompareTag("Player")) return;

        GameManager.Instance.AddScore(value);
        Destroy(gameObject);
    }
}
using UnityEngine;

public class Patroller : MonoBehaviour
{
    public float speed = 2f;
    public float patrolDistance = 3f;

    Vector3 start;
    int direction = 1;

    void Start()
    {
        start = transform.position;
    }

    void Update()
    {
        transform.Translate(Vector2.right * direction * speed * Time.deltaTime);

        if (Mathf.Abs(transform.position.x - start.x) >= patrolDistance)
        {
            direction *= -1;
            transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, 1f);
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            collision.gameObject.GetComponent<PlayerHealth>()?.TakeDamage(1);
        }
    }
}

The pieces

  • A coin's collider is a trigger (Is Trigger checked), so the player passes through it while still getting OnTriggerEnter2D, and it destroys itself once collected.
  • The patroller walks back and forth by tracking distance from its start position, and flips its direction (and its sprite, via localScale.x) at each end.
  • OnCollisionEnter2D on the enemy fires when the player touches its solid collider, that's the difference from the coin: an enemy should physically be there (block/push the player), a coin shouldn't.
  • GetComponent<PlayerHealth>()?.TakeDamage(1) uses the null-conditional ?. in case the colliding object somehow doesn't have a PlayerHealth component, avoiding a crash.

TIP

Give enemies and hazards a distinct Tag (e.g. "Enemy", "Hazard") and coins a "Collectible" tag. Tag checks (CompareTag) are far cheaper than GetComponent calls just to identify what something is.

📝 Collectibles & Enemies Quiz

Passing score: 70%
  1. 1.Why is a coin's collider set to Is Trigger instead of a solid collider?

  2. 2.CompareTag(...) is a cheaper way to check what a GameObject is than calling ____ just to check if a component exists.

  3. 3.An enemy that should physically block the player should use a trigger collider instead of a solid one.