先创建单列模式
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T:Component //泛型写法 where 限制 为 component
{
//作为泛型变量 单列模式
public static T instance { get; private set; }
protected virtual void Awake()//pritected 只能继承的使用 virtual可以重写
{
instance=this as T;//将本身转为 泛型
}
}
再创建音乐管理类,继承单列
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : Singleton<AudioManager>
{
[SerializeField] AudioSource SFXplayer;//AudioSource播放器
[SerializeField] float Min_PITH=0.9f;
[SerializeField] float Max_PITH=1.1f;
public void PlaySFXaudio(AudioData audioData)
{
// SFXplayer.clip= audioClip;
// SFXplayer.volume= volume;
// SFXplayer.Play();//无法播放复数音乐 会重重之前播放的音乐
SFXplayer.PlayOneShot(audioData.audioClip,audioData.volume);
}
//播放随机音调
public void PlayRandomSFXaudio(AudioData audioData)
{
SFXplayer.pitch=Random.Range(Min_PITH,Max_PITH);
PlaySFXaudio(audioData);
}
//播放随机音乐
public void PlayRandomSFXaudio(AudioData[] audioData)
{
PlayRandomSFXaudio(audioData[Random.Range(0,audioData.Length)]);
}
}
[System.Serializable] public class AudioData// [System.Serializable] 序列化到编辑器中
{
public AudioClip audioClip;
public float volume;
}
使用方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GamePlayUIController : MonoBehaviour
{
[Header("---Audio---")]
[SerializeField] AudioData pauseSFX;
public void Pause()
{
AudioManager.instance.PlaySFXaudio(pauseSFX);
}
}
再创建一个持久化单列
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class presisterSingleton<T>: MonoBehaviour where T : Component
{
public static T instance
{
get;
private set;
}//可以被其他类访问 只能被本类赋值
protected virtual void Awake()
{
//避免加载多个 持续性脚本
if(instance == null)
{
instance=this as T;//as运算符:转换不成功得到一个null值,不会抛出异常 转换类型
}
else
{
Destroy(instance);
}
DontDestroyOnLoad(gameObject);
}
}