Skip to content

Instantly share code, notes, and snippets.

@nekonenene
Created May 23, 2019 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nekonenene/3643fe8e958fc8bd54d64215d65e73c8 to your computer and use it in GitHub Desktop.
Save nekonenene/3643fe8e958fc8bd54d64215d65e73c8 to your computer and use it in GitHub Desktop.
オーディオのフェードイン・フェードアウト:DOTween 使用(ブログ公開用)
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Audio;
using DG.Tweening;
// Singleton として持ち続ける
public class SoundManager : MonoBehaviour {
static SoundManager instance;
public AudioMixerGroup BGMMixerGroup;
public AudioMixerGroup SEMixerGroup;
GameObject soundObject;
AudioMixer mixer;
AudioSource bgmSource;
static string bgmVolumeParam = "BGMVolume";
static string seVolumeParam = "SEVolume";
static float defaultVolume = 0.8f; // 0 dB
void Awake() {
if (instance == null) {
instance = this;
mixer = BGMMixerGroup.audioMixer;
createSoundObject();
DontDestroyOnLoad(this.gameObject);
} else {
Destroy(this.gameObject);
}
}
void createSoundObject() {
soundObject = new GameObject("SoundObject");
GameObject.DontDestroyOnLoad(soundObject);
bgmSource = soundObject.AddComponent<AudioSource>();
}
public static void PlayBGM(string path) {
instance.playBGM(path);
}
void playBGM(string path) {
DOTween.Kill(instance.mixer);
SetBGMMixerVolume(defaultVolume);
var clip = Resources.Load<AudioClip>(path);
bgmSource.clip = clip;
bgmSource.outputAudioMixerGroup = BGMMixerGroup;
bgmSource.loop = true;
bgmSource.Play();
Resources.UnloadUnusedAssets();
}
public static void SetBGMMixerVolume(float volume = 0.8f) {
instance.mixer.SetFloat(bgmVolumeParam, volumeToDecibel(volume));
}
public static void SetSEMixerVolume(float volume = 0.8f) {
instance.mixer.SetFloat(seVolumeParam, volumeToDecibel(volume));
}
public static void FadeInBGM(float fadeDuration = 2.0f) {
instance.mixer.DOSetFloat(bgmVolumeParam, volumeToDecibel(defaultVolume), fadeDuration)
.From(volumeToDecibel(0))
.SetEase(Ease.InCubic);
}
public static void FadeOutBGM(float fadeDuration = 2.0f) {
instance.mixer.DOSetFloat(bgmVolumeParam, volumeToDecibel(0), fadeDuration)
.From(volumeToDecibel(defaultVolume))
.SetEase(Ease.InSine);
}
static float volumeToDecibel(float volume) {
return volume * 100 - 80; // -80dB ~ +20dB
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment