using UnityEngine;
using UnityEngine.Events;
namespace UnityAgent
{
///
/// Collectible pickup. Triggers an event when collected and adds to the
/// global PickupSystem score.
///
[RequireComponent(typeof(Collider))]
public class Pickup : MonoBehaviour
{
public int value = 10;
public AudioClip collectClip;
public UnityEvent onCollected;
private void Reset()
{
GetComponent().isTrigger = true;
}
private void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player")) return;
PickupSystem.Instance?.Collect(value);
onCollected?.Invoke();
if (collectClip != null && PickupSystem.Instance != null)
PickupSystem.Instance.PlayPickupSound(collectClip);
Destroy(gameObject);
}
}
///
/// Singleton that tracks the player's score and plays pickup sounds.
///
public class PickupSystem : MonoBehaviour
{
public static PickupSystem Instance { get; private set; }
public int score { get; private set; }
public AudioSource audioSource;
public System.Action onScoreChanged;
private void Awake()
{
if (Instance != null && Instance != this) { Destroy(gameObject); return; }
Instance = this;
if (audioSource == null) audioSource = gameObject.AddComponent();
}
public void Collect(int amount)
{
score += amount;
onScoreChanged?.Invoke(score);
}
public void PlayPickupSound(AudioClip clip)
{
if (audioSource != null && clip != null) audioSource.PlayOneShot(clip);
}
}
}