File size: 1,831 Bytes
40c0886
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using UnityEngine;
using UnityEngine.Events;

namespace UnityAgent
{
    /// <summary>
    /// Collectible pickup. Triggers an event when collected and adds to the
    /// global PickupSystem score.
    /// </summary>
    [RequireComponent(typeof(Collider))]
    public class Pickup : MonoBehaviour
    {
        public int value = 10;
        public AudioClip collectClip;
        public UnityEvent onCollected;

        private void Reset()
        {
            GetComponent<Collider>().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);
        }
    }

    /// <summary>
    /// Singleton that tracks the player's score and plays pickup sounds.
    /// </summary>
    public class PickupSystem : MonoBehaviour
    {
        public static PickupSystem Instance { get; private set; }

        public int score { get; private set; }
        public AudioSource audioSource;

        public System.Action<int> onScoreChanged;

        private void Awake()
        {
            if (Instance != null && Instance != this) { Destroy(gameObject); return; }
            Instance = this;
            if (audioSource == null) audioSource = gameObject.AddComponent<AudioSource>();
        }

        public void Collect(int amount)
        {
            score += amount;
            onScoreChanged?.Invoke(score);
        }

        public void PlayPickupSound(AudioClip clip)
        {
            if (audioSource != null && clip != null) audioSource.PlayOneShot(clip);
        }
    }
}