unity 全局音频播放

2018-02-01  本文已影响0人  Walk_In_Jar

EffectAudioManager.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EffectAudioManager : MonoBehaviour
{
    public static EffectAudioManager _instacne;
    private AudioSource audioSource;
    public static EffectAudioManager Instance
    {
        get
        {
            if (_instacne == null)
            {
                _instacne = FindObjectOfType<EffectAudioManager>();
                DontDestroyOnLoad(_instacne.gameObject);
            }
            return _instacne;
        }
    }

    internal void PlayAudioSource(string name)
    {
        if (!audioSource)
        {
            audioSource = GetComponent<AudioSource>();
        }
        if (audioSource.clip == null)
        {
            audioSource.clip = Resources.Load<AudioClip>("Sounds/" + name);
        }
        else
        {
            if (audioSource.clip.name != name)
                audioSource.clip = Resources.Load<AudioClip>("Sounds/" + name);
        }
        audioSource.Play();
    }
    private void Awake()
    {
        if (_instacne == null)
        {
            _instacne = this;
            DontDestroyOnLoad(this);
        }
        else if (this != _instacne)
        {
            Destroy(gameObject);
        }
    }
}

调用 EffectAudioManager.Instance.PlayAudioSource("count");

上一篇下一篇

猜你喜欢

热点阅读