-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSound.cs
More file actions
55 lines (49 loc) · 2.15 KB
/
Sound.cs
File metadata and controls
55 lines (49 loc) · 2.15 KB
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
using DG.Tweening;
using UnityEngine;
public static class Sound {
const float pitchVariance = 0.2f;
const float volumeVariance = 0.15f;
static AudioSource GetNewSoundSource() {
var gameObject = new GameObject();
Object.DontDestroyOnLoad(gameObject);
return gameObject.AddComponent<AudioSource>();
}
static AudioSource universalSource = null;
public static void PlayClipUniversal(SoundEffect sound) {
if (universalSource == null) {
universalSource = GetNewSoundSource();
}
PlayClip(universalSource, sound);
}
public static void PlayClip(AudioSource source, SoundEffect sound) {
if (source == null) {
Debug.LogError("Trying to play sound with null AudioSource");
return;
}
if (sound == null) {
Debug.LogError("Trying to play sound with null SoundEffect");
return;
}
var randPitch = Random.Range(sound.pitch - (sound.pitch * pitchVariance), sound.pitch + (sound.pitch * pitchVariance));
var randVol = Random.Range(sound.volume - (sound.volume * volumeVariance), sound.volume + (sound.volume * volumeVariance));
source.pitch = randPitch;
source.PlayOneShot(sound.sound, randVol);
}
static AudioSource fadeInOutSource = null;
public static async void PlayClipFadeInOut(SoundEffect sound, float startTime, float fadeInTime, float totalDuration, float fadeOutTime, float volume = -1f, float pitch = -1f) {
if (fadeInOutSource == null) {
fadeInOutSource = GetNewSoundSource();
}
if (volume == -1f) volume = sound.volume;
if (pitch == -1f) pitch = sound.pitch;
fadeInOutSource.pitch = pitch;
fadeInOutSource.clip = sound.sound;
fadeInOutSource.time = startTime;
fadeInOutSource.Play();
fadeInOutSource.volume = 0f;
fadeInOutSource.DOFade(volume, fadeInTime).SetEase(Ease.InCirc);
await Awaitable.WaitForSecondsAsync(totalDuration - fadeOutTime);
await fadeInOutSource.DOFade(0f, fadeOutTime).SetEase(Ease.OutSine).AsyncWaitForCompletion();
fadeInOutSource.Stop();
}
}