Skip to content

Instantly share code, notes, and snippets.

@yuseinishiyama
Last active January 3, 2016 13:09
Show Gist options
  • Save yuseinishiyama/8467468 to your computer and use it in GitHub Desktop.
Save yuseinishiyama/8467468 to your computer and use it in GitHub Desktop.
Manage background music. (For Unity3d)
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);
});
}
}
@yuseinishiyama
Copy link
Author

Usage:

bgmManager.Play ("best_song_ever");

or you can choose more safety way

if (bgmManager.PrepareClipWithName ("best_song_ever")) {
bgmManager.Play ();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment