Source file unity-csharp/ebook/CoinPickup.cs from the GDnD code examples. Download raw file

// Demonstrates a 2D trigger pickup for The Architecture of Play ebook.
// Referenced by: docs/ebook/GDnD-Architecture-of-Play.md
// Related pages: [[unity-collider2d-and-triggers]], [[unity-gamemanager-pattern]], [[unity-prefabs-scripting]]
using UnityEngine;
 
public class CoinPickup : MonoBehaviour
{
    [SerializeField] private GameManager gameManager;
    [SerializeField] private CoinPickupFeedback feedback;
    [SerializeField] private int scoreValue = 10;
 
    private bool collected;
 
    // A coin spawned from a prefab cannot have the scene's GameManager dragged
    // into its field, so PickupSpawner passes it in straight after Instantiate.
    public void SetGameManager(GameManager manager)
    {
        gameManager = manager;
    }
 
    private void OnTriggerEnter2D(Collider2D other)
    {
        // Guard: the coin stays in the scene for a moment while its feedback
        // plays, and a player with two colliders can enter twice in one step.
        if (collected || !other.CompareTag("Player"))
        {
            return;
        }
 
        collected = true;
        gameManager.AddScore(scoreValue);
 
        if (feedback != null)
        {
            feedback.Play();
        }
        else
        {
            Destroy(gameObject);
        }
    }
}