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 Triggerchecked), so the player passes through it while still gettingOnTriggerEnter2D, and it destroys itself once collected. - The patroller walks back and forth by tracking distance from its
startposition, and flips itsdirection(and its sprite, vialocalScale.x) at each end. OnCollisionEnter2Don 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 aPlayerHealthcomponent, 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.