5.5 Placing and Programming Collectibles

Collectibles like coins or stars are common gameplay elements.

Step 1: Create a Collectible Object

  1. Add a 3D or 2D object (e.g., a star model or sprite).
  2. Add a Collider component and check Is Trigger.

Step 2: Create a Collectible Script
Attach this script to the collectible object:

void OnTriggerEnter(Collider other) {
    if (other.CompareTag("Player")) {
        Debug.Log("Collected an item!");
        Destroy(gameObject);
    }
}

Step 3: Add Points to the Score
Modify the script to update the player’s score:

public int points = 10;

void OnTriggerEnter(Collider other) {
    if (other.CompareTag("Player")) {
        GameManager.instance.AddScore(points);
        Destroy(gameObject);
    }
}

Test It: Run the game, collect the item, and observe the feedback.