Created
October 3, 2017 10:04
-
-
Save kunofellasleep/4caa001ff3df2920b76b82bfa9f3e9e2 to your computer and use it in GitHub Desktop.
Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UniRx; | |
/// <summary> | |
/// 指定のフォルダ(targetPath)に音声ファイルをいれて | |
/// SoundEffectManager.Instance.Play("filename"); で再生できる | |
/// </summary> | |
public class SoundEffectManager : MonoBehaviour { | |
//Instanceにアタッチする音声再生用のコンポーネント | |
static private AudioSource audioSource; | |
//使う音声ファイルをいれとくやつ | |
static private Dictionary<string, AudioClip> audios; | |
//Resorcesフォルダからのパス | |
static private string targetPath = "SE"; | |
private void Awake () { | |
//音声ファイルを全てロードして、ファイル名を紐付けとく | |
audios = new Dictionary<string, AudioClip> (); | |
object[] files = Resources.LoadAll (targetPath); | |
foreach (AudioClip file in files) { | |
audios [file.name] = file; | |
} | |
} | |
/// <summary> | |
/// 音の再生 | |
/// </summary> | |
public void Play (string filename, float delaySec = 0.0f, float volume = 1.0f) { | |
audioSource.volume = volume; | |
Observable.Timer(TimeSpan.FromMilliseconds(delaySec * 1000)) | |
.Subscribe(_ => | |
audioSource.PlayOneShot (audios [filename] as AudioClip)); | |
} | |
/// <summary> | |
/// 音の停止 | |
/// </summary> | |
public void Stop () { | |
audioSource.Stop (); | |
} | |
/// <summary> | |
/// Singleton | |
/// </summary> | |
private static SoundEffectManager _instance; | |
public static SoundEffectManager Instance { | |
get { | |
if( _instance == null ) { | |
GameObject go = new GameObject ("SoundEffectManager"); | |
_instance = go.AddComponent<SoundEffectManager>(); | |
audioSource = go.AddComponent<AudioSource> (); | |
audioSource.playOnAwake = false; | |
// シーン遷移するとき破棄されないように | |
DontDestroyOnLoad (go); | |
} | |
return _instance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment