音效系统

版权声明:转载或者引用本文内容请注明来源及原作者 https://blog.csdn.net/TIANHUNYISHUI/article/details/88814923
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Framework {
	/// <summary>
	/// 音效系统
	/// </summary>
	public class SoundSystem : MonoSingleton<SoundSystem> {
		private const string LOG_ASSET = "Can't find out sound asset:{0}";
		private const string LOG_GET = "Can't find out sound by id:{0}";

		/// <summary>
		/// 音效对象池
		/// </summary>
		private ObjectPool m_SoundPool = new ObjectPool (OnSoundConstruct, OnSoundDestroy, OnSoundEnabled, OnSoundDisabled);

		/// <summary>
		/// 销毁回调
		/// </summary>
		private void OnDestroy () {
			Clear ();
		}

		/// <summary>
		/// 播放音效
		/// </summary>
		/// <param name="soundName">音效名</param>
		/// <param name="loop">是否循环</param>
		/// <returns>返回音效对象</returns>
		public static SoundObject Play (string soundName, bool loop = false) {
			AudioClip resource = GetAsset (soundName);
			SoundObject soundObject = Instance.m_SoundPool.Get () as SoundObject;

			soundObject.Play (resource, loop);
			return soundObject;
		}

		/// <summary>
		/// 清理音效
		/// </summary>
		public static void Clear () {
			Instance.m_SoundPool.Clear ();
		}

		/// <summary>
		/// 获取音效资源
		/// </summary>
		/// <param name="soundName">音效名</param>
		/// <returns>返回资源对象</returns>
		private static AudioClip GetAsset (string soundName) {
			string name = soundName.Substring (soundName.LastIndexOf ('/') + 1);
			name = name.Remove (name.LastIndexOf ('.'));
			AudioClip asset = AssetSystem.Load (soundName, name, typeof (AudioClip)) as AudioClip;

			if (asset == null) {
				Debug.LogError (string.Format (LOG_ASSET, soundName));
			}

			return asset;
		}

		/// <summary>
		/// 音效构造
		/// </summary>
		/// <returns>返回音效对象</returns>
		private static object OnSoundConstruct () {
			GameObject gameObject = new GameObject ();
			gameObject.transform.SetParent (Instance.transform, false);
			SoundObject soundObject = gameObject.AddComponent<SoundObject> ();
			return soundObject;
		}

		/// <summary>
		/// 音效销毁回调
		/// </summary>
		/// <param name="obj">销毁的对象</param>
		private static void OnSoundDestroy (object obj) {
			SoundObject soundObject = obj as SoundObject;
			soundObject.Stop (true);
		}

		/// <summary>
		/// 音效开启回调
		/// </summary>
		/// <param name="obj">对象</param>
		private static void OnSoundEnabled (object obj) {
			SoundObject soundObject = obj as SoundObject;
			soundObject.OnStopEvent += OnSoundStop;
		}

		/// <summary>
		/// 音效关闭回调
		/// </summary>
		/// <param name="obj"></param>
		private static void OnSoundDisabled (object obj) {

		}

		/// <summary>
		/// 音效停止回调
		/// </summary>
		/// <param name="soundObject">音效对象</param>
		private static void OnSoundStop (SoundObject soundObject) {
			Instance.m_SoundPool.Remove (soundObject);
		}
	}

}

猜你喜欢

转载自blog.csdn.net/TIANHUNYISHUI/article/details/88814923