Skip to content

Instantly share code, notes, and snippets.

@boj
Created February 6, 2012 07:37
Show Gist options
  • Save boj/1750484 to your computer and use it in GitHub Desktop.
Save boj/1750484 to your computer and use it in GitHub Desktop.
Audio Management
using UnityEngine;
using System.Collections;
public class AudioManager : MonoBehaviour {
public GameObject audioChannelPrefab;
private AudioSource[] audioChannels = new AudioSource[12]; // 12 channels
void Start() {
for (int i = 0; i < audioChannels.Length; i++) {
GameObject channel = Instantiate(audioChannelPrefab) as GameObject;
audioChannels[i] = channel.GetComponent<AudioSource>();
}
}
AudioSource GetFreeChannel() {
for (int i = 0; i < audioChannels.Length; i++) {
if (!audioChannels[i].isPlaying) {
return audioChannels[i];
}
}
return null;
}
public void Play(AudioClip clip, Vector3 location, float pitch) {
AudioSource channel = GetFreeChannel();
if (channel == null) return; // no available channels
// set transform position
channel.transform.position = location;
// play clip
channel.clip = clip;
channel.pitch = pitch;
channel.Play();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment