chenxin
2020-11-06 fe4457c2ff07dcea1cccd6886188a334ef9c196b
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
65
66
67
68
69
70
71
72
73
74
75
76
77
using UnityEngine;
 
namespace ActionGameFramework.Audio
{
    /// <summary>
    /// A helper for playing random audio clips
    /// The randomness is not uniform but rather based on weights
    /// </summary>
    [RequireComponent(typeof(AudioSource))]
    public class RandomAudioSource : MonoBehaviour
    {
        /// <summary>
        /// A weighted list of audio clips
        /// </summary>
        public WeightedAudioList clips;
 
        /// <summary>
        /// Configuration for playing a sound randomly on awake
        /// </summary>
        public bool playOnEnabled;
 
        /// <summary>
        /// The attached audio source
        /// </summary>
        protected AudioSource m_Source;
 
        /// <summary>
        /// Cache the audio source and play if necessary
        /// </summary>
        protected virtual void OnEnable()
        {
            if (m_Source == null)
            {
                m_Source = GetComponent<AudioSource>();
            }
            if (playOnEnabled)
            {
                PlayRandomClip();
            }
        }
 
        /// <summary>
        /// Plays the random clip using the attached audio source
        /// </summary>
        public virtual void PlayRandomClip()
        {
            if (m_Source == null)
            {
                m_Source = GetComponent<AudioSource>();
            }
            PlayRandomClip(m_Source);
        }
 
        /// <summary>
        /// Plays the random clip using a specified audio source
        /// </summary>
        /// <param name="source">Audio source to use</param>
        public virtual void PlayRandomClip(AudioSource source)
        {
            if (source == null)
            {
                Debug.LogError("[RANDOM AUDIO SOURCE] Missing audio source");
                return;
            }
 
            AudioClip clip = clips.WeightedSelection();
            if (clip == null)
            {
                Debug.LogError("[RANDOM AUDIO SOURCE] Missing audio clips");
                return;
            }
 
            //source.clip = clip;
            //source.Play();
        }
    }
}