Last active
January 3, 2016 13:09
-
-
Save yuseinishiyama/8467468 to your computer and use it in GitHub Desktop.
Manage background music.
(For Unity3d)
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 UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
[AddComponentMenu("Scripts/BGM/BGMManager")] | |
public class BGMManager : MonoBehaviour | |
{ | |
AudioSource audioSource; | |
public List<AudioClip> audioClips ; | |
public string BgmName { | |
get { | |
return audioSource.clip.name; | |
} | |
} | |
void Start () | |
{ | |
audioSource = GetComponent <AudioSource> (); | |
} | |
public bool Play () | |
{ | |
return Play (BgmName); | |
} | |
public bool Play (string bgmName) | |
{ | |
if (PrepareClipWithName (bgmName)) { | |
audioSource.Play (); | |
return true; | |
} else { | |
Debug.LogWarning ("Invalid BGM."); | |
return false; | |
} | |
} | |
public void Stop () | |
{ | |
audioSource.Stop (); | |
} | |
public bool PrepareClipWithName (string name) | |
{ | |
return (audioSource.clip = FindClipWithName (name)); | |
} | |
AudioClip FindClipWithName (string name) | |
{ | |
return audioClips.Find ( | |
delegate(AudioClip obj) { | |
return (obj.name == name); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
bgmManager.Play ("best_song_ever");
or you can choose more safety way
if (bgmManager.PrepareClipWithName ("best_song_ever")) {
bgmManager.Play ();
}