AudioManager是一个空对象
using UnityEngine;
[System .Serializable ]
public class Sound
{
public string name;
public AudioClip clip;
[Range(0f, 1f)]
public float volume;
[Range(-3f, 3f)]
public float pitch;
public bool loop = false;
[HideInInspector]//在检查器窗口中隐藏
public AudioSource source;
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public static AudioManager Instance;
public Sound[] sounds;
void Start()
{
if (Instance != null )
{
Destroy(gameObject);
}
else
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
foreach (Sound s in sounds)//循环数组
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
public void Play(string sound)
{
Sound s = Array.Find(sounds, item => item.name == sound);
s.source.Play();
}
public void Stop(string sound)
{
Sound s = Array.Find(sounds, item => item.name == sound);
s.source.Stop();
}
}